From 6f6bfe3c462976e3ebd8e734d2088a710d4f1413 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Dec 2026 17:35:51 +0100 Subject: [PATCH] Cut 7a: recursive OrdnanceNode runtime, 5-mfg procedural weapons, Union(13) net seam --- src/RustToDust.Core/Catalog.cs | 20 + src/RustToDust.Core/GridChassis.cs | 5 +- src/RustToDust.Core/MatchRules.cs | 12 +- src/RustToDust.Core/MatchState.cs | 54 +- src/RustToDust.Core/OrbitalDropSystem.cs | 21 +- src/RustToDust.Core/OrdnanceGraph.cs | 430 ++++ src/RustToDust.Core/ProceduralWeapons.cs | 1895 +++++++++++++++++ src/RustToDust.Core/SimEvents.cs | 25 +- src/RustToDust.Core/SpectatorRing.cs | 27 +- src/RustToDust.Net/RemoteArenaSession.cs | 11 +- src/RustToDust.Net/ServerMatchHost.cs | 25 + src/RustToDust.Ymir/ArenaSession.cs | 713 ++++--- src/RustToDust.Ymir/OrdnanceRuntime.cs | 1795 ++++++++++++++++ .../OrdnanceAndProceduralWeaponTests.cs | 660 ++++++ 14 files changed, 5371 insertions(+), 322 deletions(-) create mode 100644 src/RustToDust.Core/OrdnanceGraph.cs create mode 100644 src/RustToDust.Core/ProceduralWeapons.cs create mode 100644 src/RustToDust.Ymir/OrdnanceRuntime.cs create mode 100644 tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs diff --git a/src/RustToDust.Core/Catalog.cs b/src/RustToDust.Core/Catalog.cs index 381c7ab..8a7ca81 100644 --- a/src/RustToDust.Core/Catalog.cs +++ b/src/RustToDust.Core/Catalog.cs @@ -481,6 +481,26 @@ namespace RustToDust.Core public static readonly IReadOnlyDictionary ModulesById = AllModules.ToDictionary(m => m.Id, StringComparer.OrdinalIgnoreCase); + public static bool TryGetModule(string? id, out ModuleSpec spec) + { + if (string.IsNullOrEmpty(id)) + { + spec = null!; + return false; + } + if (ModulesById.TryGetValue(id, out spec!)) + { + return true; + } + if (ProceduralWeaponGenerator.TryParseId(id, out var key)) + { + spec = ProceduralWeaponGenerator.Generate(key).Module; + return true; + } + spec = null!; + return false; + } + public static ChassisGrid CreateStarterBuggy() { var grid = new ChassisGrid(Jackal); diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs index 83573d7..8979b54 100644 --- a/src/RustToDust.Core/GridChassis.cs +++ b/src/RustToDust.Core/GridChassis.cs @@ -64,7 +64,10 @@ namespace RustToDust.Core int BurstCount, bool IsWideArc = false, float MinPitchDeg = -15f, - float MaxPitchDeg = 45f) + float MaxPitchDeg = 45f, + WeaponVisualClass? VisualClassOverride = null, + float EffectivePowerScore = 0f, + ProceduralWeaponSpec? Procedural = null) { /// /// Exact Aetheria trapezoidal plateau curve: diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs index af11df2..31ccac9 100644 --- a/src/RustToDust.Core/MatchRules.cs +++ b/src/RustToDust.Core/MatchRules.cs @@ -900,8 +900,18 @@ namespace RustToDust.Core } } + public static float GetModulePowerScore(ModuleSpec mod) => + mod.EffectivePowerScore > 0f + ? mod.EffectivePowerScore + : mod.WeaponDamage * MathF.Max(1, mod.BurstCount); + private static bool IsBetterModule(ModuleSpec candidate, ModuleSpec current) { + if (candidate.Kind == HardpointKind.Weapon && current.Kind == HardpointKind.Weapon) + { + return GetModulePowerScore(candidate) > GetModulePowerScore(current); + } + if (candidate.IsImperial && !current.IsImperial) { return true; @@ -909,8 +919,6 @@ namespace RustToDust.Core return candidate.Kind switch { - HardpointKind.Weapon => candidate.WeaponDamage * MathF.Max(1, candidate.BurstCount) > - current.WeaponDamage * MathF.Max(1, current.BurstCount), HardpointKind.Engine => candidate.ThrustBonus > current.ThrustBonus, HardpointKind.Radiator => candidate.CoolingPower > current.CoolingPower, HardpointKind.Armor => candidate.ArmorBonus > current.ArmorBonus, diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index 3551af1..28bd77a 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -23,10 +23,14 @@ namespace RustToDust.Core public enum WeaponVisualClass { - KineticLight, - Autocannon, - Explosive, - ThermalBeam + KineticLight = 0, + Autocannon = 1, + Explosive = 2, + ThermalBeam = 3, + GaussRail = 4, + PlasmaPpc = 5, + RocketSalvo = 6, + SwarmSmart = 7 } public enum HitTargetKind @@ -402,11 +406,15 @@ namespace RustToDust.Core public long AllocateHitEventId() => _nextHitEventId++; public int AllocateTracerId() => _nextTracerId++; + public static WeaponVisualClass ClassifyWeaponVisual(ModuleSpec mod) => + mod.VisualClassOverride ?? ClassifyWeaponVisual(mod.Id); + public static WeaponVisualClass ClassifyWeaponVisual(string weaponId) => weaponId switch { "autocannon" => WeaponVisualClass.Autocannon, "flak" or "recoilless" => WeaponVisualClass.Explosive, "gilded_lance" or "touring_plasma" or "aegis_pd" => WeaponVisualClass.ThermalBeam, + _ when ProceduralWeaponGenerator.TryParseId(weaponId, out var key) => ProceduralWeaponGenerator.Generate(key).VisualClass, _ => WeaponVisualClass.KineticLight }; @@ -953,16 +961,24 @@ namespace RustToDust.Core targets.Add((dx, dz, chassisPool[i], null)); } - // 26 ground salvage module drops spread across canyons, passes, and ruins (including 1x1 Wide-Arc PD!) + // 26 ground salvage module drops spread across canyons, passes, and ruins (including 1x1 Wide-Arc PD + 10 deterministic procedural weapons!) ModuleSpec[] salvagePool = { Catalog.Autocannon, Catalog.Flak, Catalog.PointDefenseFlak, Catalog.Recoilless, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, - Catalog.DieselCore, Catalog.PointDefenseFlak, Catalog.Autocannon, Catalog.Flak, - Catalog.Recoilless, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, - Catalog.Autocannon, Catalog.PointDefenseFlak, Catalog.Recoilless, Catalog.Flak, - Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, - Catalog.Autocannon, Catalog.ImperialAegisPd + Catalog.DieselCore, Catalog.PointDefenseFlak, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 0).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 1).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 2).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 3).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 4).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 5).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 6).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 7).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 8).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 9).Module }; for (int i = 0; i < salvagePool.Length; i++) @@ -1241,11 +1257,19 @@ namespace RustToDust.Core { Catalog.Autocannon, Catalog.Flak, Catalog.PointDefenseFlak, Catalog.Recoilless, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, - Catalog.DieselCore, Catalog.PointDefenseFlak, Catalog.Autocannon, Catalog.Flak, - Catalog.Recoilless, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, - Catalog.Autocannon, Catalog.PointDefenseFlak, Catalog.Recoilless, Catalog.Flak, - Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, - Catalog.Autocannon, Catalog.ImperialAegisPd + Catalog.DieselCore, Catalog.PointDefenseFlak, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 0).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 1).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 2).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 3).Module, + ProceduralWeaponGenerator.RollForWave(0, (ulong)Seed, 4).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 5).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 6).Module, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 7).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 8).Module, + ProceduralWeaponGenerator.RollForWave(1, (ulong)Seed, 9).Module }; for (int i = 0; i < salvagePool.Length; i++) diff --git a/src/RustToDust.Core/OrbitalDropSystem.cs b/src/RustToDust.Core/OrbitalDropSystem.cs index a7c00a0..5bb0097 100644 --- a/src/RustToDust.Core/OrbitalDropSystem.cs +++ b/src/RustToDust.Core/OrbitalDropSystem.cs @@ -1079,7 +1079,7 @@ namespace RustToDust.Core private void LaunchScheduledWave(int waveIndex, DropSurfaceQuery surfaceQuery) { _currentWaveIndex = waveIndex; - var gearSpecs = BuildEscalatingWaveGear(waveIndex); + var gearSpecs = BuildEscalatingWaveGear(waveIndex, _state.Seed); var gearTargets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(gearSpecs.Count); float safeR = MathF.Max(65f, _state.Spectators.SafeRadius * 0.68f); @@ -1150,16 +1150,17 @@ namespace RustToDust.Core } } - private static List<(ChassisSpec? Chassis, ModuleSpec? Module)> BuildEscalatingWaveGear(int waveIndex) + private static List<(ChassisSpec? Chassis, ModuleSpec? Module)> BuildEscalatingWaveGear(int waveIndex, int matchSeed) { var list = new List<(ChassisSpec?, ModuleSpec?)>(8); + ulong seed = (ulong)(uint)matchSeed; switch (waveIndex) { case 1: list.Add((Catalog.Hornet, null)); list.Add((Catalog.Condor, null)); - list.Add((null, Catalog.Autocannon)); - list.Add((null, Catalog.Recoilless)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(1, seed, 10).Module)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(1, seed, 11).Module)); list.Add((null, Catalog.Flak)); list.Add((null, Catalog.TurboCore)); list.Add((null, Catalog.CopperRad)); @@ -1168,8 +1169,8 @@ namespace RustToDust.Core case 2: list.Add((Catalog.Paladin, null)); list.Add((Catalog.Manticore, null)); - list.Add((null, Catalog.GildedLance)); - list.Add((null, Catalog.TouringPlasma)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(2, seed, 20).Module)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(2, seed, 21).Module)); list.Add((null, Catalog.ImperialAegisPd)); list.Add((null, Catalog.NobleCore)); list.Add((null, Catalog.GoldRadiator)); @@ -1178,8 +1179,8 @@ namespace RustToDust.Core default: list.Add((Catalog.Bastion, null)); list.Add((Catalog.Kestrel, null)); - list.Add((null, Catalog.GildedLance)); - list.Add((null, Catalog.TouringPlasma)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(3, seed, 30).Module)); + list.Add((null, ProceduralWeaponGenerator.RollForWave(3, seed, 31).Module)); list.Add((null, Catalog.ImperialAegisPd)); list.Add((null, Catalog.NobleCore)); break; @@ -1477,7 +1478,7 @@ namespace RustToDust.Core WaveIndex = dto.WaveIndex, ContenderId = dto.ContenderId, Chassis = dto.ChassisId is not null && Catalog.ChassisById.TryGetValue(dto.ChassisId, out var cs) ? cs : null, - Module = dto.ModuleId is not null && Catalog.ModulesById.TryGetValue(dto.ModuleId, out var ms) ? ms : null, + Module = Catalog.TryGetModule(dto.ModuleId, out var ms) ? ms : null, AllowFlatRoofLanding = allowFlatRoof, TargetX = dto.X, TargetZ = dto.Z, @@ -1558,7 +1559,7 @@ namespace RustToDust.Core WaveIndex = ev.WaveIndex, ContenderId = ev.ContenderId, Chassis = ev.ChassisId is not null && Catalog.ChassisById.TryGetValue(ev.ChassisId, out var cs) ? cs : null, - Module = ev.ModuleId is not null && Catalog.ModulesById.TryGetValue(ev.ModuleId, out var ms) ? ms : null, + Module = Catalog.TryGetModule(ev.ModuleId, out var ms) ? ms : null, AllowFlatRoofLanding = allowFlatRoof, TargetX = ev.X, TargetZ = ev.Z, diff --git a/src/RustToDust.Core/OrdnanceGraph.cs b/src/RustToDust.Core/OrdnanceGraph.cs new file mode 100644 index 0000000..4952c6b --- /dev/null +++ b/src/RustToDust.Core/OrdnanceGraph.cs @@ -0,0 +1,430 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum ManufacturerId : byte + { + ScrapFrontier = 0, + KorrathiIronworks = 1, + AuralianOptics = 2, + VexNineCollective = 3, + ThalassanForge = 4 + } + + public enum WeaponArchetypeKind : byte + { + // ScrapFrontier (0..3) + RotaryAutocannon = 0, + FlakBurstCannon = 1, + SabotSlugCannon = 2, + DumbRocketPod = 3, + + // KorrathiIronworks (4..7) + SabotRocketSled = 4, + MirvMineBlanket = 5, + ClusterSiegeMortar = 6, + GyrojetBunkerBuster = 7, + + // AuralianOptics (8..11) + LoiteringLaserDrone = 8, + RefractingPrismLance = 9, + PulsedBeamSweeper = 10, + ThermalOverloadOrb = 11, + + // VexNineCollective (12..15) + HomingSwarmPod = 12, + AirburstProximitySwarm = 13, + SmartSpiderMineTrap = 14, + PointDefenseWeb = 15, + + // ThalassanForge (16..19) + HypervelocityGaussRail = 16, + PlasmaPoolMortar = 17, + ArcDischargeLance = 18, + RailPlasmaBeam = 19 + } + + public enum OrdnanceAudioClass : byte + { + CannonLight = 0, + CannonHeavy = 1, + RocketSalvo = 2, + LaserHeavy = 3, + GaussRail = 4, + PlasmaPpc = 5 + } + + public enum OrdnanceMotion : byte + { + HitscanBeam = 0, + Ballistic = 1, + RocketBoosted = 2, + HomingMissile = 3, + LoiterOrbit = 4, + StationaryMine = 5 + } + + public enum OrdnanceTriggerKind : byte + { + Impact = 0, + Timeout = 1, + Altitude = 2, + Proximity = 3, + StageElapsed = 4, + Apex = 5 + } + + public enum OrdnanceTriggerAction : byte + { + Detonate = 0, + Split = 1, + Transition = 2, + Fizzle = 3 + } + + public enum OrdnanceVisualShape : byte + { + None = 0, + Bolt = 1, + Rocket = 2, + SabotCarrier = 3, + Drone = 4, + Mine = 5, + Pool = 6 + } + + public sealed class OrdnanceTriggerRule + { + public OrdnanceTriggerKind Kind { get; init; } + public float Threshold { get; init; } + public float MinAge { get; init; } + public OrdnanceTriggerAction Action { get; init; } + public OrdnanceNodeDef? ChildNode { get; init; } + public int SplitCount { get; init; } = 1; + public float SplitConeDeg { get; init; } = 30f; + public bool EjectSabotVfx { get; init; } + } + + public sealed class OrdnanceWhileAliveDef + { + public float Interval { get; init; } = 0.5f; + public int MaxPulses { get; init; } = 8; + public float TriggerScanRadius { get; init; } = 95f; + public bool RequireHostileTarget { get; init; } = true; + public float TargetConeDeg { get; init; } = 75f; + public OrdnanceNodeDef? ChildNode { get; init; } + public float RadialHeat { get; init; } + public float RadialDamage { get; init; } + public float RadialRadius { get; init; } + } + + public sealed class OrdnanceNodeDef + { + public const int MaxAllowedDepth = 4; + public const int MaxShotSubSpawnBudget = 16; + + public byte DefIndex { get; internal set; } + public byte Depth { get; internal set; } + + public OrdnanceMotion Motion { get; init; } = OrdnanceMotion.HitscanBeam; + public float InitialSpeed { get; init; } = 220f; + public float LaunchPitchBiasDeg { get; init; } + public float GravityScale { get; init; } = 1f; + public float ThrustAccel { get; init; } + public float BurnTime { get; init; } + public float MaxSpeed { get; init; } + public float TurnRateRad { get; init; } + public float SeekerConeDeg { get; init; } = 60f; + public float SeekerRange { get; init; } = 220f; + public float LoiterAltitudeAgl { get; init; } = 35f; + public float LoiterOrbitRadius { get; init; } = 15f; + public float LoiterOrbitSpeedRad { get; init; } = 1.45f; + public float ArmDelay { get; init; } + public float ProximityRadius { get; init; } + public bool ProximityIgnoreOwner { get; init; } = true; + public bool IsThermalPool { get; init; } + public float InterceptHp { get; init; } + public float MaxLifetime { get; init; } = 5f; + public float Range { get; init; } = 200f; + + public float DirectDamage { get; init; } + public float SplashDamage { get; init; } + public float SplashRadius { get; init; } + public float HeatTransfer { get; init; } + public float CraterRadius { get; init; } + public float CraterDepth { get; init; } + public float ScorchRadius { get; init; } + public bool CraterFirstBurstOnly { get; init; } + public byte MaxPenetrations { get; init; } + public float PenetrationDamageDecay { get; init; } = 0.72f; + public bool IsAirburst { get; init; } + + public OrdnanceWhileAliveDef? WhileAlive { get; init; } + public OrdnanceTriggerRule[] Triggers { get; init; } = Array.Empty(); + + public WeaponVisualClass VisualClass { get; init; } = WeaponVisualClass.KineticLight; + public OrdnanceAudioClass AudioClass { get; init; } = OrdnanceAudioClass.CannonLight; + public uint ColorRgba { get; init; } = 0xFFE888FFu; + public float TracerTtl { get; init; } = 0.10f; + public OrdnanceVisualShape VisualShape { get; init; } = OrdnanceVisualShape.Bolt; + } + + public static class OrdnanceGraphValidator + { + public static OrdnanceNodeDef[] ValidateAndFlatten(OrdnanceNodeDef root) + { + ArgumentNullException.ThrowIfNull(root); + + var activeStack = new HashSet(ReferenceEqualityComparer.Instance); + var visited = new List(8); + var visitedSet = new Dictionary(ReferenceEqualityComparer.Instance); + + int peakConcurrent = ValidateNode(root, depth: 0, activeStack, visited, visitedSet); + if (peakConcurrent > OrdnanceNodeDef.MaxShotSubSpawnBudget) + { + throw new InvalidOperationException( + $"OrdnanceNodeDef sub-spawn budget {peakConcurrent} exceeds MaxShotSubSpawnBudget {OrdnanceNodeDef.MaxShotSubSpawnBudget}."); + } + + if (visited.Count > 32) + { + throw new InvalidOperationException($"OrdnanceNodeDef tree exceeds 32 flattened nodes (got {visited.Count})."); + } + + for (int i = 0; i < visited.Count; i++) + { + visited[i].DefIndex = (byte)i; + visited[i].Depth = visitedSet[visited[i]]; + } + + return visited.ToArray(); + } + + private static int ValidateNode( + OrdnanceNodeDef node, + int depth, + HashSet activeStack, + List visited, + Dictionary visitedSet) + { + if (depth >= OrdnanceNodeDef.MaxAllowedDepth) + { + throw new InvalidOperationException( + $"OrdnanceNodeDef depth {depth} violates MaxAllowedDepth ({OrdnanceNodeDef.MaxAllowedDepth}, valid 0..{OrdnanceNodeDef.MaxAllowedDepth - 1})."); + } + + if (!activeStack.Add(node)) + { + throw new InvalidOperationException("Cyclic OrdnanceNodeDef graph detected."); + } + + ValidateFiniteFields(node); + + if (!visitedSet.TryGetValue(node, out byte prevDepth)) + { + visitedSet[node] = (byte)depth; + visited.Add(node); + } + else if (depth > prevDepth) + { + visitedSet[node] = (byte)depth; + } + + int maxBranchMultiplier = 1; + + if (node.WhileAlive is { } wa) + { + if (!float.IsFinite(wa.Interval) || wa.Interval <= 0f || + !float.IsFinite(wa.TriggerScanRadius) || + !float.IsFinite(wa.TargetConeDeg) || + !float.IsFinite(wa.RadialDamage) || + !float.IsFinite(wa.RadialHeat) || + !float.IsFinite(wa.RadialRadius)) + { + throw new InvalidOperationException("OrdnanceWhileAliveDef contains invalid non-finite or non-positive values."); + } + + if (wa.ChildNode is not null) + { + int childBudget = ValidateNode(wa.ChildNode, depth + 1, activeStack, visited, visitedSet); + if (wa.ChildNode.Motion != OrdnanceMotion.HitscanBeam) + { + int pulses = Math.Clamp(wa.MaxPulses, 1, 32); + maxBranchMultiplier = Math.Max(maxBranchMultiplier, pulses * childBudget); + } + } + } + + if (node.Triggers is not null) + { + for (int i = 0; i < node.Triggers.Length; i++) + { + var tr = node.Triggers[i]; + if (!float.IsFinite(tr.Threshold) || !float.IsFinite(tr.MinAge) || !float.IsFinite(tr.SplitConeDeg)) + { + throw new InvalidOperationException("OrdnanceTriggerRule contains non-finite values."); + } + + if (tr.Action == OrdnanceTriggerAction.Split) + { + if (tr.SplitCount < 1 || tr.SplitCount > OrdnanceNodeDef.MaxShotSubSpawnBudget) + { + throw new InvalidOperationException( + $"OrdnanceTriggerRule.SplitCount={tr.SplitCount} must be in [1..{OrdnanceNodeDef.MaxShotSubSpawnBudget}]."); + } + if (tr.ChildNode is null) + { + throw new InvalidOperationException("Split trigger requires non-null ChildNode."); + } + int childBudget = ValidateNode(tr.ChildNode, depth + 1, activeStack, visited, visitedSet); + maxBranchMultiplier = Math.Max(maxBranchMultiplier, tr.SplitCount * childBudget); + } + else if (tr.Action == OrdnanceTriggerAction.Transition) + { + if (tr.ChildNode is null) + { + throw new InvalidOperationException("Transition trigger requires non-null ChildNode."); + } + int childBudget = ValidateNode(tr.ChildNode, depth + 1, activeStack, visited, visitedSet); + maxBranchMultiplier = Math.Max(maxBranchMultiplier, childBudget); + } + } + } + + activeStack.Remove(node); + return maxBranchMultiplier; + } + + private static void ValidateFiniteFields(OrdnanceNodeDef n) + { + bool valid = + float.IsFinite(n.InitialSpeed) && n.InitialSpeed >= 0f && + float.IsFinite(n.LaunchPitchBiasDeg) && + float.IsFinite(n.GravityScale) && + float.IsFinite(n.ThrustAccel) && n.ThrustAccel >= 0f && + float.IsFinite(n.BurnTime) && n.BurnTime >= 0f && + float.IsFinite(n.MaxSpeed) && n.MaxSpeed >= 0f && + float.IsFinite(n.TurnRateRad) && n.TurnRateRad >= 0f && + float.IsFinite(n.SeekerConeDeg) && + float.IsFinite(n.SeekerRange) && n.SeekerRange >= 0f && + float.IsFinite(n.LoiterAltitudeAgl) && + float.IsFinite(n.LoiterOrbitRadius) && n.LoiterOrbitRadius >= 0f && + float.IsFinite(n.LoiterOrbitSpeedRad) && + float.IsFinite(n.ArmDelay) && n.ArmDelay >= 0f && + float.IsFinite(n.ProximityRadius) && n.ProximityRadius >= 0f && + float.IsFinite(n.InterceptHp) && n.InterceptHp >= 0f && + float.IsFinite(n.MaxLifetime) && n.MaxLifetime >= 0f && + float.IsFinite(n.Range) && n.Range >= 0f && + float.IsFinite(n.DirectDamage) && n.DirectDamage >= 0f && + float.IsFinite(n.SplashDamage) && n.SplashDamage >= 0f && + float.IsFinite(n.SplashRadius) && n.SplashRadius >= 0f && + float.IsFinite(n.HeatTransfer) && n.HeatTransfer >= 0f && + float.IsFinite(n.CraterRadius) && n.CraterRadius >= 0f && + float.IsFinite(n.CraterDepth) && n.CraterDepth >= 0f && + float.IsFinite(n.ScorchRadius) && n.ScorchRadius >= 0f && + float.IsFinite(n.PenetrationDamageDecay) && + float.IsFinite(n.TracerTtl) && n.TracerTtl >= 0f; + + if (!valid) + { + throw new InvalidOperationException("OrdnanceNodeDef contains non-finite or negative scalar field."); + } + } + } + + public static class OrdnanceCatalogMapper + { + private static readonly Dictionary _legacyById = new(StringComparer.OrdinalIgnoreCase); + + static OrdnanceCatalogMapper() + { + RegisterLegacy(Catalog.Mg762, WeaponVisualClass.KineticLight, OrdnanceAudioClass.CannonLight, 0xFFE888FFu, 0.09f); + RegisterLegacy(Catalog.Autocannon, WeaponVisualClass.Autocannon, OrdnanceAudioClass.CannonHeavy, 0xFF9933FFu, 0.10f); + RegisterLegacy(Catalog.Flak, WeaponVisualClass.Explosive, OrdnanceAudioClass.CannonHeavy, 0xFF6622FFu, 0.12f, + craterRadius: 2.0f, craterDepth: 0.35f, craterFirstBurstOnly: true); + RegisterLegacy(Catalog.PointDefenseFlak, WeaponVisualClass.KineticLight, OrdnanceAudioClass.CannonLight, 0xFF8833FFu, 0.09f, + isAirburst: true); + RegisterLegacy(Catalog.Recoilless, WeaponVisualClass.Explosive, OrdnanceAudioClass.CannonHeavy, 0xFF6622FFu, 0.12f, + craterRadius: 4.2f, craterDepth: 1.05f, scorchRadius: 4.5f); + RegisterLegacy(Catalog.GildedLance, WeaponVisualClass.ThermalBeam, OrdnanceAudioClass.LaserHeavy, 0xFFD966FFu, 0.13f); + RegisterLegacy(Catalog.TouringPlasma, WeaponVisualClass.ThermalBeam, OrdnanceAudioClass.PlasmaPpc, 0x5CE6FFFFu, 0.13f); + RegisterLegacy(Catalog.ImperialAegisPd, WeaponVisualClass.ThermalBeam, OrdnanceAudioClass.LaserHeavy, 0x5CE6FFFFu, 0.13f); + } + + private static void RegisterLegacy( + ModuleSpec spec, + WeaponVisualClass visual, + OrdnanceAudioClass audio, + uint colorRgba, + float tracerTtl, + float craterRadius = 0f, + float craterDepth = 0f, + float scorchRadius = 0f, + bool craterFirstBurstOnly = false, + bool isAirburst = false) + { + var root = BuildHitscanFromSpec(spec, visual, audio, colorRgba, tracerTtl, craterRadius, craterDepth, scorchRadius, craterFirstBurstOnly, isAirburst); + OrdnanceGraphValidator.ValidateAndFlatten(root); + _legacyById[spec.Id] = root; + } + + public static OrdnanceNodeDef ResolveRoot(ModuleSpec spec) + { + if (spec.Procedural is { } proc) + { + return proc.RootNode; + } + + if (_legacyById.TryGetValue(spec.Id, out var cached)) + { + return cached; + } + + var visual = MatchState.ClassifyWeaponVisual(spec); + var fallback = BuildHitscanFromSpec(spec, visual, OrdnanceAudioClass.CannonLight, 0xFFE888FFu, 0.10f); + OrdnanceGraphValidator.ValidateAndFlatten(fallback); + return fallback; + } + + private static OrdnanceNodeDef BuildHitscanFromSpec( + ModuleSpec spec, + WeaponVisualClass visual, + OrdnanceAudioClass audio, + uint colorRgba, + float tracerTtl, + float craterRadius = 0f, + float craterDepth = 0f, + float scorchRadius = 0f, + bool craterFirstBurstOnly = false, + bool isAirburst = false) + { + return new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = MathF.Max(100f, spec.ProjectileSpeed), + Range = MathF.Max(5f, spec.WeaponRange), + DirectDamage = spec.WeaponDamage, + HeatTransfer = spec.HeatOutput * 0.25f, + CraterRadius = craterRadius, + CraterDepth = craterDepth, + ScorchRadius = scorchRadius, + CraterFirstBurstOnly = craterFirstBurstOnly, + IsAirburst = isAirburst, + VisualClass = visual, + AudioClass = audio, + ColorRgba = colorRgba, + TracerTtl = tracerTtl, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Impact, + Action = OrdnanceTriggerAction.Detonate + } + } + }; + } + } +} diff --git a/src/RustToDust.Core/ProceduralWeapons.cs b/src/RustToDust.Core/ProceduralWeapons.cs new file mode 100644 index 0000000..4809e57 --- /dev/null +++ b/src/RustToDust.Core/ProceduralWeapons.cs @@ -0,0 +1,1895 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using MessagePack; + +namespace RustToDust.Core +{ + [MessagePackObject] + public readonly record struct ProceduralWeaponKey( + [property: Key(0)] ulong Seed, + [property: Key(1)] byte Manufacturer, + [property: Key(2)] byte Archetype, + [property: Key(3)] byte Tier, + [property: Key(4)] byte Flags); + + public readonly record struct ModularWeaponAssembly( + byte ReceiverIdx, + byte BarrelIdx, + byte FeedIdx, + byte MuzzleIdx, + ManufacturerId Palette, + float VisualScale, + bool IsWideArc) + { + public string ReceiverPartName => ProceduralWeaponParts.ReceiverNames[ReceiverIdx & 3]; + public string BarrelPartName => ProceduralWeaponParts.BarrelNames[BarrelIdx & 3]; + public string FeedPartName => ProceduralWeaponParts.FeedNames[FeedIdx & 3]; + public string MuzzlePartName => ProceduralWeaponParts.MuzzleNames[MuzzleIdx & 3]; + } + + public static class ProceduralWeaponParts + { + public static readonly string[] ReceiverNames = + { + "rx_salvage_frame", + "rx_korrathi_cradle", + "rx_auralian_prism", + "rx_vex_pod_rack" + }; + + public static readonly string[] BarrelNames = + { + "brl_autocannon", + "brl_sabot_rail", + "brl_prism_lance", + "brl_missile_tube" + }; + + public static readonly string[] FeedNames = + { + "fd_belt_drum", + "fd_rotary_loader", + "fd_capacitor_bank", + "fd_swarm_magazine" + }; + + public static readonly string[] MuzzleNames = + { + "mz_slotted_brake", + "mz_mirv_warhead", + "mz_loiter_aero_fin", + "mz_plasma_diffuser" + }; + } + + public sealed class ProceduralWeaponSpec + { + public required ProceduralWeaponKey Key { get; init; } + public required ManufacturerId Manufacturer { get; init; } + public required WeaponArchetypeKind Archetype { get; init; } + public required byte WaveTier { get; init; } + public required string DisplayName { get; init; } + public required string ManufacturerLabel { get; init; } + public required string SummaryLine1 { get; init; } + public required string SummaryLine2 { get; init; } + public required WeaponVisualClass VisualClass { get; init; } + public required OrdnanceAudioClass AudioClass { get; init; } + public required ModularWeaponAssembly Assembly { get; init; } + public required OrdnanceNodeDef RootNode { get; init; } + public required OrdnanceNodeDef[] FlattenedNodes { get; init; } + public required float PowerScore { get; init; } + public required float RecoilMultiplier { get; init; } + public required ModuleSpec Module { get; init; } + } + + public static class ProceduralWeaponGenerator + { + private const int MaxCacheEntries = 2048; + private static readonly ConcurrentDictionary _cache = new(); + + private static readonly string[] MfgCodes = { "SCR", "KOR", "AUR", "VEX", "THL" }; + + private static readonly string[] MfgLabels = + { + "Scrap-Frontier Armament", + "Korrathi Ironworks", + "Auralian Optics", + "Vex-Nine Collective", + "Thalassan Forge" + }; + + private static readonly string[][] PrefixPools = + { + new[] { "Rustbucket", "Gutter", "Jury-Rigged", "Wrenchborn", "Scrapyard" }, + new[] { "Korrathi", "Bastion-Breaker", "Slag-Hammer", "Ironjaw", "Redline" }, + new[] { "Auralian", "Sol-7", "Sun-Glass", "Helios", "Prism-Born" }, + new[] { "Vex-Nine", "Bramble", "Hive-Mind", "Neuro-Weave", "Widowmaker" }, + new[] { "Thalassan", "Abyssal", "Voltaic", "Tide-Breaker", "Deep-Arc" } + }; + + private static readonly string[] TierTags = { "Mk-I", "Mk-II", "Mk-III", "Apex" }; + + private static readonly uint[] MfgColors = + { + 0xFFAA33FFu, // ScrapFrontier amber + 0xF2C422FFu, // Korrathi hazard yellow/orange + 0x38E8FFFFu, // Auralian cyan-gold + 0x7CF230FFu, // Vex-Nine violet-lime + 0x2CB8FFFFu // Thalassan electric blue + }; + + public static string FormatId(ProceduralWeaponKey key) + { + int mfg = Math.Clamp((int)key.Manufacturer, 0, MfgCodes.Length - 1); + int arch = Math.Clamp((int)key.Archetype, 0, 19); + int tier = key.Tier & 0xF; + int flags = key.Flags & 0xF; + return $"proc:{MfgCodes[mfg]}:{arch:X2}:{tier:X1}{flags:X1}:{key.Seed:X16}"; + } + + public static bool TryParseId(string? id, out ProceduralWeaponKey key) + { + key = default; + if (string.IsNullOrWhiteSpace(id) || !id.StartsWith("proc:", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string[] parts = id.Split(':'); + if (parts.Length != 5) + { + return false; + } + + int mfgIdx = -1; + for (int i = 0; i < MfgCodes.Length; i++) + { + if (string.Equals(parts[1], MfgCodes[i], StringComparison.OrdinalIgnoreCase)) + { + mfgIdx = i; + break; + } + } + if (mfgIdx < 0) + { + return false; + } + + if (!byte.TryParse(parts[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte arch) || arch >= 20) + { + return false; + } + + if (parts[3].Length != 2 || + !byte.TryParse(parts[3].AsSpan(0, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte tier) || + !byte.TryParse(parts[3].AsSpan(1, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte flags)) + { + return false; + } + + if (!ulong.TryParse(parts[4], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong seed)) + { + return false; + } + + key = new ProceduralWeaponKey(seed, (byte)mfgIdx, arch, tier, flags); + return true; + } + + public static ProceduralWeaponSpec CreateDreamSabotSled(ulong seed = 0x5AB0700010001UL, byte tier = 2) => + Generate(new ProceduralWeaponKey(seed, (byte)ManufacturerId.KorrathiIronworks, (byte)WeaponArchetypeKind.SabotRocketSled, tier, 1)); + + public static ProceduralWeaponSpec CreateDreamLoiteringDrone(ulong seed = 0xD204E00020002UL, byte tier = 3) => + Generate(new ProceduralWeaponKey(seed, (byte)ManufacturerId.AuralianOptics, (byte)WeaponArchetypeKind.LoiteringLaserDrone, tier, 1)); + + public static ProceduralWeaponSpec CreateDreamMirvMineBlanket(ulong seed = 0xB1A4E00030003UL, byte tier = 2) => + Generate(new ProceduralWeaponKey(seed, (byte)ManufacturerId.KorrathiIronworks, (byte)WeaponArchetypeKind.MirvMineBlanket, tier, 1)); + + public static ProceduralWeaponSpec CreateDreamWeapon(WeaponArchetypeKind archetype, ulong seed = 0xCAFE00001UL, byte tier = 2) + { + byte mfg = (byte)((int)archetype / 4); + return Generate(new ProceduralWeaponKey(seed, mfg, (byte)archetype, tier, 1)); + } + + public static ProceduralWeaponSpec RollForWave(int wave, ulong matchSeed, int ordinal) + { + ulong h = Mix64(matchSeed ^ ((ulong)(uint)wave * 0x9E3779B97F4A7C15UL) ^ ((ulong)(uint)ordinal * 0xBF58476D1CE4E5B9UL)); + int clampedWave = Math.Clamp(wave, 0, 3); + ManufacturerId mfg = clampedWave switch + { + 0 => (h & 3) == 0 ? ManufacturerId.KorrathiIronworks : ManufacturerId.ScrapFrontier, + 1 => (h % 3) switch + { + 0 => ManufacturerId.ScrapFrontier, + 1 => ManufacturerId.KorrathiIronworks, + _ => ManufacturerId.VexNineCollective + }, + 2 => (h % 3) switch + { + 0 => ManufacturerId.KorrathiIronworks, + 1 => ManufacturerId.VexNineCollective, + _ => ManufacturerId.AuralianOptics + }, + _ => (h % 4) switch + { + 0 => ManufacturerId.KorrathiIronworks, + 1 => ManufacturerId.AuralianOptics, + 2 => ManufacturerId.VexNineCollective, + _ => ManufacturerId.ThalassanForge + } + }; + + byte arch = (byte)((int)mfg * 4 + (int)((h >> 8) & 3)); + return Generate(new ProceduralWeaponKey(h, (byte)mfg, arch, (byte)clampedWave, 0)); + } + + public static ProceduralWeaponSpec RollForManufacturer(ManufacturerId mfg, int tier, ulong seed) + { + ulong h = Mix64(seed ^ ((ulong)(byte)mfg * 0x94D049BB133111EBUL)); + byte arch = (byte)((int)mfg * 4 + (int)((h >> 6) & 3)); + byte clampedTier = (byte)Math.Clamp(tier, 0, 3); + return Generate(new ProceduralWeaponKey(h, (byte)mfg, arch, clampedTier, 0)); + } + + public static ProceduralWeaponSpec Generate(ProceduralWeaponKey key) + { + var normalized = NormalizeKey(key); + if (_cache.TryGetValue(normalized, out var existing)) + { + return existing; + } + + if (_cache.Count >= MaxCacheEntries) + { + _cache.Clear(); + } + + var built = BuildSpec(normalized); + _cache[normalized] = built; + return built; + } + + private static ProceduralWeaponKey NormalizeKey(ProceduralWeaponKey key) + { + byte mfg = (byte)Math.Clamp((int)key.Manufacturer, 0, 4); + byte arch = (byte)Math.Clamp((int)key.Archetype, 0, 19); + byte tier = (byte)(key.Tier & 3); + byte flags = (byte)(key.Flags & 0xF); + return new ProceduralWeaponKey(key.Seed, mfg, arch, tier, flags); + } + + private static ProceduralWeaponSpec BuildSpec(ProceduralWeaponKey key) + { + var mfg = (ManufacturerId)key.Manufacturer; + var arch = (WeaponArchetypeKind)key.Archetype; + byte tier = key.Tier; + bool isCanonicalDream = (key.Flags & 1) != 0; + + ulong rng = Mix64(key.Seed ^ ((ulong)key.Manufacturer << 48) ^ ((ulong)key.Archetype << 32) ^ ((ulong)tier << 16) ^ key.Flags); + + var (rx, brl, fd, mz) = SelectModularParts(mfg, arch, isCanonicalDream, ref rng); + float tierScale = 1f + tier * 0.14f; + float rollDmg = isCanonicalDream ? 1f : Lerp(0.92f, 1.12f, NextFloat(ref rng)); + float rollCd = isCanonicalDream ? 1f : Lerp(0.92f, 1.08f, NextFloat(ref rng)); + float rollHeat = isCanonicalDream ? 1f : Lerp(0.92f, 1.08f, NextFloat(ref rng)); + + // Receiver modifiers + float rxDmgMult = rx switch { 1 => 1.32f, _ => 1.0f }; + float rxCdMult = rx switch { 1 => 1.25f, _ => 1.0f }; + float rxHeatMult = rx switch { 0 => 0.88f, 1 => 1.30f, _ => 1.0f }; + float rxSpreadMult = rx switch { 2 => 0.45f, _ => 1.0f }; + float rxRangeMult = rx switch { 2 => 1.20f, _ => 1.0f }; + int rxBurstAdd = rx == 3 ? 1 : 0; + float rxThermalMassAdd = rx == 0 ? 5f : 0f; + float rxRecoilMult = rx switch { 0 => 1.15f, 2 => 0f, _ => 1.0f }; + + // Barrel modifiers + float brlVelMult = brl == 0 ? 1.25f : 1.0f; + float brlCdMult = brl == 0 ? 0.85f : 1.0f; + float brlEnergyMult = brl == 2 ? 1.25f : 1.0f; + + // Feed modifiers + float fdHeatMult = fd switch { 0 => 0.85f, 1 => 1.28f, 2 => 1.22f, _ => 1.0f }; + float fdCdMult = fd switch { 0 => 0.90f, 1 => 0.68f, _ => 1.0f }; + float fdSpreadAdd = fd == 1 ? 0.012f : 0f; + float fdEnergyMult = fd == 2 ? 1.28f : 1.0f; + float fdThermalMassAdd = fd == 2 ? 4f : 0f; + int fdSplitAdd = fd == 3 ? 3 : 0; + + // Muzzle modifiers + float mzSpreadMult = mz == 0 ? 0.70f : 1.0f; + float mzRecoilMult = mz == 0 ? 0.80f : 1.0f; + + float mfgRecoil = mfg switch + { + ManufacturerId.ScrapFrontier => 1.20f, + ManufacturerId.KorrathiIronworks => 1.45f, + ManufacturerId.AuralianOptics => 0.0f, + ManufacturerId.VexNineCollective => 0.75f, + _ => 0.55f + }; + float recoilMult = mfgRecoil * rxRecoilMult * mzRecoilMult; + + string prefix = PrefixPools[(int)mfg][(int)(NextU64(ref rng) % (ulong)PrefixPools[(int)mfg].Length)]; + string tierTag = TierTags[tier & 3]; + uint colorRgba = MfgColors[(int)mfg]; + + bool isWideArc = arch == WeaponArchetypeKind.PointDefenseWeb; + var assembly = new ModularWeaponAssembly(rx, brl, fd, mz, mfg, VisualScale: 1.0f, IsWideArc: isWideArc); + + var buildCtx = new ArchetypeBuildContext + { + Mfg = mfg, + Arch = arch, + Tier = tier, + TierScale = tierScale, + RollDmg = rollDmg, + RollCd = rollCd, + RollHeat = rollHeat, + RxDmgMult = rxDmgMult, + RxCdMult = rxCdMult, + RxHeatMult = rxHeatMult, + RxSpreadMult = rxSpreadMult, + RxRangeMult = rxRangeMult, + RxBurstAdd = rxBurstAdd, + RxThermalMassAdd = rxThermalMassAdd, + BrlVelMult = brlVelMult, + BrlCdMult = brlCdMult, + BrlEnergyMult = brlEnergyMult, + FdHeatMult = fdHeatMult, + FdCdMult = fdCdMult, + FdSpreadAdd = fdSpreadAdd, + FdEnergyMult = fdEnergyMult, + FdThermalMassAdd = fdThermalMassAdd, + FdSplitAdd = fdSplitAdd, + MzSpreadMult = mzSpreadMult, + BarrelIdx = brl, + MuzzleIdx = mz, + ColorRgba = colorRgba, + Prefix = prefix, + TierTag = tierTag, + IsCanonicalDream = isCanonicalDream + }; + + var built = BuildArchetype(buildCtx); + var flattened = OrdnanceGraphValidator.ValidateAndFlatten(built.Root); + + float powerScore = ComputePowerScore(built.Root, built.BurstCount, built.Cooldown, built.DirectSummaryDmg); + string id = FormatId(key); + bool isImperial = mfg != ManufacturerId.ScrapFrontier; + + var modSpec = new ModuleSpec( + Id: id, + Name: built.DisplayName, + Kind: HardpointKind.Weapon, + Width: 1, + Height: built.Height, + IsImperial: isImperial, + ThermalMass: MathF.Max(5f, built.ThermalMass), + Conductivity: built.Conductivity, + OptimalTemp: built.OptimalTemp, + PlateauWidth: built.PlateauWidth, + MinTemp: 0f, + MaxTemp: built.MaxTemp, + HeatOutput: MathF.Max(8f, built.HeatOutput), + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: built.DirectSummaryDmg, + WeaponRange: built.Range, + FireCooldown: MathF.Max(0.10f, built.Cooldown), + ProjectileSpeed: built.DisplaySpeed, + SpreadRad: MathF.Max(0.001f, built.SpreadRad), + BurstCount: Math.Max(1, built.BurstCount), + IsWideArc: isWideArc, + MinPitchDeg: isWideArc ? -10f : -15f, + MaxPitchDeg: isWideArc ? 85f : 45f, + VisualClassOverride: built.VisualClass, + EffectivePowerScore: powerScore); + + var spec = new ProceduralWeaponSpec + { + Key = key, + Manufacturer = mfg, + Archetype = arch, + WaveTier = tier, + DisplayName = built.DisplayName, + ManufacturerLabel = MfgLabels[(int)mfg], + SummaryLine1 = built.SummaryLine1, + SummaryLine2 = built.SummaryLine2, + VisualClass = built.VisualClass, + AudioClass = built.AudioClass, + Assembly = assembly, + RootNode = built.Root, + FlattenedNodes = flattened, + PowerScore = powerScore, + RecoilMultiplier = recoilMult, + Module = modSpec with { Procedural = null } // temporary placeholder replaced below + }; + + var finalModule = modSpec with { Procedural = spec }; + return new ProceduralWeaponSpec + { + Key = spec.Key, + Manufacturer = spec.Manufacturer, + Archetype = spec.Archetype, + WaveTier = spec.WaveTier, + DisplayName = spec.DisplayName, + ManufacturerLabel = spec.ManufacturerLabel, + SummaryLine1 = spec.SummaryLine1, + SummaryLine2 = spec.SummaryLine2, + VisualClass = spec.VisualClass, + AudioClass = spec.AudioClass, + Assembly = spec.Assembly, + RootNode = spec.RootNode, + FlattenedNodes = spec.FlattenedNodes, + PowerScore = spec.PowerScore, + RecoilMultiplier = spec.RecoilMultiplier, + Module = finalModule + }; + } + + private static (byte Rx, byte Brl, byte Fd, byte Mz) SelectModularParts( + ManufacturerId mfg, + WeaponArchetypeKind arch, + bool isCanonicalDream, + ref ulong rng) + { + if (isCanonicalDream) + { + return arch switch + { + WeaponArchetypeKind.SabotRocketSled => (1, 1, 0, 0), + WeaponArchetypeKind.LoiteringLaserDrone => (2, 3, 2, 2), + WeaponArchetypeKind.MirvMineBlanket => (3, 3, 3, 1), + _ => ((byte)mfg switch { 0 => (byte)0, 1 => (byte)1, 2 => (byte)2, 3 => (byte)3, _ => (byte)2 }, + (byte)((int)arch & 3), + (byte)(((int)arch + 1) & 3), + (byte)(((int)arch + 2) & 3)) + }; + } + + byte rx = arch switch + { + WeaponArchetypeKind.SabotRocketSled => 1, + WeaponArchetypeKind.LoiteringLaserDrone => 2, + WeaponArchetypeKind.MirvMineBlanket => (NextU64(ref rng) & 1) == 0 ? (byte)3 : (byte)1, + _ => (byte)(NextU64(ref rng) % 4) + }; + byte brl = arch switch + { + WeaponArchetypeKind.SabotRocketSled or WeaponArchetypeKind.HypervelocityGaussRail => 1, + WeaponArchetypeKind.LoiteringLaserDrone or WeaponArchetypeKind.MirvMineBlanket or WeaponArchetypeKind.HomingSwarmPod => 3, + WeaponArchetypeKind.RefractingPrismLance or WeaponArchetypeKind.RailPlasmaBeam => 2, + _ => (byte)(NextU64(ref rng) % 4) + }; + byte fd = arch switch + { + WeaponArchetypeKind.MirvMineBlanket or WeaponArchetypeKind.HomingSwarmPod or WeaponArchetypeKind.AirburstProximitySwarm => 3, + WeaponArchetypeKind.LoiteringLaserDrone or WeaponArchetypeKind.ArcDischargeLance or WeaponArchetypeKind.PlasmaPoolMortar => 2, + _ => (byte)(NextU64(ref rng) % 4) + }; + byte mz = arch switch + { + WeaponArchetypeKind.MirvMineBlanket or WeaponArchetypeKind.ClusterSiegeMortar or WeaponArchetypeKind.AirburstProximitySwarm => 1, + WeaponArchetypeKind.LoiteringLaserDrone => 2, + WeaponArchetypeKind.PlasmaPoolMortar or WeaponArchetypeKind.ArcDischargeLance or WeaponArchetypeKind.ThermalOverloadOrb => 3, + _ => (byte)(NextU64(ref rng) % 4) + }; + + return (rx, brl, fd, mz); + } + + private sealed class ArchetypeBuildContext + { + public ManufacturerId Mfg; + public WeaponArchetypeKind Arch; + public byte Tier; + public float TierScale; + public float RollDmg; + public float RollCd; + public float RollHeat; + public float RxDmgMult; + public float RxCdMult; + public float RxHeatMult; + public float RxSpreadMult; + public float RxRangeMult; + public int RxBurstAdd; + public float RxThermalMassAdd; + public float BrlVelMult; + public float BrlCdMult; + public float BrlEnergyMult; + public float FdHeatMult; + public float FdCdMult; + public float FdSpreadAdd; + public float FdEnergyMult; + public float FdThermalMassAdd; + public int FdSplitAdd; + public float MzSpreadMult; + public byte BarrelIdx; + public byte MuzzleIdx; + public uint ColorRgba; + public string Prefix = ""; + public string TierTag = ""; + public bool IsCanonicalDream; + } + + private sealed class BuiltArchetype + { + public string DisplayName = ""; + public string SummaryLine1 = ""; + public string SummaryLine2 = ""; + public WeaponVisualClass VisualClass; + public OrdnanceAudioClass AudioClass; + public OrdnanceNodeDef Root = null!; + public int Height = 1; + public float ThermalMass = 10f; + public float Conductivity = 12f; + public float OptimalTemp = 75f; + public float PlateauWidth = 75f; + public float MaxTemp = 190f; + public float HeatOutput = 60f; + public float DirectSummaryDmg = 30f; + public float Range = 220f; + public float Cooldown = 0.5f; + public float DisplaySpeed = 240f; + public float SpreadRad = 0.02f; + public int BurstCount = 1; + } + + private static BuiltArchetype BuildArchetype(ArchetypeBuildContext c) + { + float baseDmgScale = c.TierScale * c.RollDmg * c.RxDmgMult; + float energyDmgScale = baseDmgScale * c.BrlEnergyMult * c.FdEnergyMult; + float cdScale = c.RollCd * c.RxCdMult * c.BrlCdMult * c.FdCdMult; + float heatScale = c.RollHeat * c.RxHeatMult * c.FdHeatMult; + float spreadScale = c.RxSpreadMult * c.MzSpreadMult; + float velScale = c.BrlVelMult; + + switch (c.Arch) + { + // ---- SCRAP-FRONTIER (0..3) ---- + case WeaponArchetypeKind.RotaryAutocannon: + { + float dmg = 14f * baseDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 1, 5); + float range = 200f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 260f * velScale, + Range = range, + DirectDamage = dmg, + HeatTransfer = 4f, + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.09f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Rotary Autocannon {c.TierTag}", + SummaryLine1 = $"SCR ROTARY | {dmg:F0}x{burst} DMG | {range:F0}m | 1x2", + SummaryLine2 = "Spin-up twin-drum autocannon shreds exposed hull cells", + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 2, + ThermalMass = 9f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 9f, + OptimalTemp = 70f, + PlateauWidth = 85f, + MaxTemp = 175f, + HeatOutput = 62f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.30f * cdScale, + DisplaySpeed = 260f * velScale, + SpreadRad = (0.032f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.FlakBurstCannon: + { + float dmg = 11f * baseDmgScale; + float splash = 9f * baseDmgScale; + int burst = Math.Clamp(4 + c.RxBurstAdd, 1, 6); + float range = 135f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 210f * velScale, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 3.2f, + CraterRadius = 1.6f, + CraterDepth = 0.25f, + CraterFirstBurstOnly = true, + IsAirburst = true, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.11f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Flak Scatter-Rig {c.TierTag}", + SummaryLine1 = $"SCR FLAK | {dmg:F0}x{burst} AIRBURST | {range:F0}m | 1x1", + SummaryLine2 = "Proximity-timed shrapnel clouds scour light armor & rotors", + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 1, + ThermalMass = 7f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 9f, + OptimalTemp = 68f, + PlateauWidth = 80f, + MaxTemp = 170f, + HeatOutput = 68f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.56f * cdScale, + DisplaySpeed = 210f * velScale, + SpreadRad = (0.11f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.SabotSlugCannon: + { + float dmg = 64f * baseDmgScale; + float speed = 340f * velScale; + float range = 270f * c.RxRangeMult; + byte pen = (byte)(c.BarrelIdx == 1 ? 2 : 1); + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = speed, + GravityScale = 0.12f, + MaxLifetime = 1.4f, + Range = range, + DirectDamage = dmg, + MaxPenetrations = pen, + PenetrationDamageDecay = 0.72f, + CraterRadius = 1.8f, + CraterDepth = 0.35f, + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.12f, + VisualShape = OrdnanceVisualShape.SabotCarrier, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 1.4f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Sabot Slug-Cannon {c.TierTag}", + SummaryLine1 = $"SCR SABOT | {dmg:F0} AP | {speed:F0}m/s | 1x2", + SummaryLine2 = $"High-velocity tungsten slug punches {pen + 1} hull layers", + VisualClass = WeaponVisualClass.Autocannon, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 10f, + OptimalTemp = 72f, + PlateauWidth = 85f, + MaxTemp = 185f, + HeatOutput = 88f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 1.05f * cdScale, + DisplaySpeed = speed, + SpreadRad = (0.012f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.DumbRocketPod: + { + float dmg = 34f * baseDmgScale; + float splash = 26f * baseDmgScale; + int burst = Math.Clamp(2 + c.RxBurstAdd, 1, 4); + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 75f * velScale, + ThrustAccel = 145f, + BurnTime = 1.2f, + MaxSpeed = 220f * velScale, + MaxLifetime = 2.6f, + Range = 250f * c.RxRangeMult, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 4.6f, + CraterRadius = 2.6f, + CraterDepth = 0.55f, + ScorchRadius = 3.2f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.6f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Rocket Salvo Pod {c.TierTag}", + SummaryLine1 = $"SCR ROCKET | {dmg + splash:F0}x{burst} HE | 220m/s | 1x2", + SummaryLine2 = "Unguided booster salvo saturates ridge lines with HE blast", + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 11f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 9f, + OptimalTemp = 70f, + PlateauWidth = 85f, + MaxTemp = 180f, + HeatOutput = 76f * heatScale, + DirectSummaryDmg = dmg + splash * 0.5f, + Range = 250f * c.RxRangeMult, + Cooldown = 1.15f * cdScale, + DisplaySpeed = 220f * velScale, + SpreadRad = (0.045f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + // ---- KORRATHI IRONWORKS (4..7) ---- + case WeaponArchetypeKind.SabotRocketSled: + { + float s0Dmg = (c.IsCanonicalDream ? 42f : 38f * baseDmgScale); + float s1Direct = (c.IsCanonicalDream ? 74f : 68f * baseDmgScale); + float s1Splash = (c.IsCanonicalDream ? 48f : 44f * baseDmgScale); + float s0Speed = c.IsCanonicalDream ? 240f : 230f * velScale; + float s1MaxSpeed = c.IsCanonicalDream ? 360f : 350f * velScale; + float range = 340f * c.RxRangeMult; + + var stage1 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 200f, + ThrustAccel = 260f, + BurnTime = 1.4f, + MaxSpeed = s1MaxSpeed, + MaxLifetime = 2.6f, + Range = range, + DirectDamage = s1Direct, + SplashDamage = s1Splash, + SplashRadius = 5.5f, + HeatTransfer = 28f, + CraterRadius = 4.2f, + CraterDepth = 1.0f, + ScorchRadius = 4.6f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.6f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = s0Speed, + GravityScale = 0.18f, + MaxLifetime = 2.0f, + Range = range, + DirectDamage = s0Dmg, + SplashDamage = 12f, + SplashRadius = 2.4f, + CraterRadius = 1.8f, + CraterDepth = 0.4f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.SabotCarrier, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.StageElapsed, + Threshold = 0.18f, + Action = OrdnanceTriggerAction.Transition, + ChildNode = stage1, + EjectSabotVfx = true + }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + return new BuiltArchetype + { + DisplayName = c.IsCanonicalDream ? $"Korrathi {c.TierTag} Sabot-Rocket Sled" : $"{c.Prefix} Sabot-Rocket Sled {c.TierTag}", + SummaryLine1 = $"KOR SABOT SLED | {s1Direct:F0}+{s1Splash:F0} AP | {s1MaxSpeed:F0}m/s | 1x2", + SummaryLine2 = "2-stage sabot sled: sheds booster at 0.18s into 360m/s AP warhead", + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 16f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 11f, + OptimalTemp = 78f, + PlateauWidth = 80f, + MaxTemp = 195f, + HeatOutput = (c.IsCanonicalDream ? 120f : 115f * heatScale), + DirectSummaryDmg = s1Direct + s1Splash, + Range = range, + Cooldown = (c.IsCanonicalDream ? 1.25f : 1.25f * cdScale), + DisplaySpeed = s1MaxSpeed, + SpreadRad = (c.IsCanonicalDream ? 0.008f : (0.010f + c.FdSpreadAdd) * spreadScale), + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.MirvMineBlanket: + { + int splitCount = c.IsCanonicalDream ? 10 : Math.Clamp(8 + c.FdSplitAdd, 6, 12); + float mineSplash = c.IsCanonicalDream ? 34f : 30f * baseDmgScale; + float range = 220f * c.RxRangeMult; + + var mineStage = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + InitialSpeed = 0f, + ArmDelay = 0.6f, + ProximityRadius = 6.5f, + ProximityIgnoreOwner = true, + MaxLifetime = 28f, + InterceptHp = 15f, + SplashDamage = mineSplash, + SplashRadius = 6.5f, + HeatTransfer = 18f, + CraterRadius = 2.2f, + CraterDepth = 0.45f, + ScorchRadius = 2.8f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Proximity, Threshold = 6.5f, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 28f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + + var bombletStage = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 26f, + GravityScale = 1.2f, + MaxLifetime = 5.0f, + DirectDamage = 12f, + SplashDamage = 18f, + SplashRadius = 3.5f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = mineStage }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 5.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 26f, + InitialSpeed = 72f, + GravityScale = 1.25f, + MaxLifetime = 4.5f, + Range = range, + DirectDamage = 25f, + SplashDamage = 24f, + SplashRadius = 4.5f, + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Apex, + MinAge = 0.25f, + Action = OrdnanceTriggerAction.Split, + ChildNode = bombletStage, + SplitCount = splitCount, + SplitConeDeg = 48f + }, + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Impact, + Action = OrdnanceTriggerAction.Split, + ChildNode = bombletStage, + SplitCount = Math.Min(6, splitCount), + SplitConeDeg = 60f + }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.5f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + return new BuiltArchetype + { + DisplayName = c.IsCanonicalDream ? $"Korrathi {c.TierTag} MIRV Mine-Blanket" : $"{c.Prefix} MIRV Mine-Blanket {c.TierTag}", + SummaryLine1 = $"KOR MIRV MINES | {splitCount}x{mineSplash:F0} PROX | {range:F0}m | 1x2", + SummaryLine2 = $"Carrier splits at apex into {splitCount} ground-armed proximity mines", + VisualClass = WeaponVisualClass.RocketSalvo, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 14f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 10f, + OptimalTemp = 76f, + PlateauWidth = 80f, + MaxTemp = 190f, + HeatOutput = (c.IsCanonicalDream ? 105f : 105f * heatScale), + DirectSummaryDmg = mineSplash * splitCount * 0.35f, + Range = range, + Cooldown = (c.IsCanonicalDream ? 1.55f : 1.55f * cdScale), + DisplaySpeed = 72f, + SpreadRad = (c.IsCanonicalDream ? 0.015f : (0.018f + c.FdSpreadAdd) * spreadScale), + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.ClusterSiegeMortar: + { + int splitCount = Math.Clamp(6 + c.FdSplitAdd, 4, 10); + float subSplash = 28f * baseDmgScale; + float range = 260f * c.RxRangeMult; + var sub = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 34f, + GravityScale = 1.35f, + MaxLifetime = 4.0f, + DirectDamage = 22f * baseDmgScale, + SplashDamage = subSplash, + SplashRadius = 5.2f, + CraterRadius = 2.8f, + CraterDepth = 0.65f, + ScorchRadius = 3.2f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 34f, + InitialSpeed = 80f, + GravityScale = 1.25f, + MaxLifetime = 4.5f, + Range = range, + DirectDamage = 35f * baseDmgScale, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Apex, MinAge = 0.30f, Action = OrdnanceTriggerAction.Split, ChildNode = sub, SplitCount = splitCount, SplitConeDeg = 40f }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Cluster Siege Mortar {c.TierTag}", + SummaryLine1 = $"KOR MORTAR | {splitCount}x{subSplash:F0} HE | {range:F0}m | 1x2", + SummaryLine2 = "High-arc siege shell bursts over cover into HE bomblets", + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.CannonHeavy, + Root = root, + Height = 2, + ThermalMass = 15f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 10f, + OptimalTemp = 78f, + PlateauWidth = 80f, + MaxTemp = 195f, + HeatOutput = 110f * heatScale, + DirectSummaryDmg = subSplash * 3.0f, + Range = range, + Cooldown = 1.65f * cdScale, + DisplaySpeed = 80f, + SpreadRad = (0.024f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.GyrojetBunkerBuster: + { + float dmg = 92f * baseDmgScale; + float splash = 58f * baseDmgScale; + float range = 290f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 110f * velScale, + ThrustAccel = 190f, + BurnTime = 1.5f, + MaxSpeed = 290f * velScale, + MaxLifetime = 2.8f, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 7.0f, + HeatTransfer = 35f, + CraterRadius = 4.8f, + CraterDepth = 1.2f, + ScorchRadius = 5.4f, + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.8f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Gyrojet Bunker-Buster {c.TierTag}", + SummaryLine1 = $"KOR GYROJET | {dmg:F0}+{splash:F0} HE | 290m/s | 1x2", + SummaryLine2 = "Heavy bunker-buster warhead excavates 4.8m craters on impact", + VisualClass = WeaponVisualClass.Explosive, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 16f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 11f, + OptimalTemp = 78f, + PlateauWidth = 80f, + MaxTemp = 195f, + HeatOutput = 135f * heatScale, + DirectSummaryDmg = dmg + splash, + Range = range, + Cooldown = 1.50f * cdScale, + DisplaySpeed = 290f * velScale, + SpreadRad = (0.015f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + // ---- AURALIAN OPTICS (8..11) ---- + case WeaponArchetypeKind.LoiteringLaserDrone: + { + float beamDmg = c.IsCanonicalDream ? 18f : 16f * energyDmgScale; + float diveDmg = c.IsCanonicalDream ? 65f : 58f * baseDmgScale; + float diveSplash = c.IsCanonicalDream ? 45f : 40f * baseDmgScale; + float range = 260f * c.RxRangeMult; + + var laserBeam = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 400f, + Range = 130f, + DirectDamage = beamDmg, + HeatTransfer = 18f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.16f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + + var diveBomb = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HomingMissile, + InitialSpeed = 48f, + ThrustAccel = 95f, + BurnTime = 2.5f, + MaxSpeed = 115f, + TurnRateRad = 5.2f, + SeekerConeDeg = 135f, + SeekerRange = 160f, + MaxLifetime = 2.5f, + DirectDamage = diveDmg, + SplashDamage = diveSplash, + SplashRadius = 6.0f, + HeatTransfer = 26f, + CraterRadius = 3.2f, + CraterDepth = 0.7f, + ScorchRadius = 3.8f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Drone, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.5f, Action = OrdnanceTriggerAction.Detonate } + } + }; + + var loiterStage = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.LoiterOrbit, + LoiterAltitudeAgl = 35f, + LoiterOrbitRadius = 15f, + LoiterOrbitSpeedRad = 1.45f, + MaxLifetime = 4.5f, + InterceptHp = 35f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Drone, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.45f, + MaxPulses = 9, + TriggerScanRadius = 110f, + RequireHostileTarget = true, + TargetConeDeg = 75f, + ChildNode = laserBeam + }, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.Timeout, + Threshold = 4.5f, + Action = OrdnanceTriggerAction.Transition, + ChildNode = diveBomb + } + } + }; + + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + LaunchPitchBiasDeg = 40f, + InitialSpeed = 52f, + ThrustAccel = 60f, + BurnTime = 1.0f, + MaxSpeed = 95f, + MaxLifetime = 2.0f, + Range = range, + DirectDamage = 40f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Drone, + Triggers = new[] + { + new OrdnanceTriggerRule + { + Kind = OrdnanceTriggerKind.StageElapsed, + Threshold = 1.1f, + Action = OrdnanceTriggerAction.Transition, + ChildNode = loiterStage + }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } + } + }; + + return new BuiltArchetype + { + DisplayName = c.IsCanonicalDream ? $"Auralian {c.TierTag} Loitering Prism-Drone" : $"{c.Prefix} Loitering Prism-Drone {c.TierTag}", + SummaryLine1 = $"AUR DRONE | 9x{beamDmg:F0} LASER + {diveDmg:F0} DIVE | 1x1", + SummaryLine2 = "Orbits at 35m AGL pulsing downward lasers, then dive-bombs on expiry", + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + Root = root, + Height = 1, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 90f, + PlateauWidth = 80f, + MaxTemp = 215f, + HeatOutput = (c.IsCanonicalDream ? 95f : 95f * heatScale), + DirectSummaryDmg = beamDmg * 5f + diveDmg, + Range = range, + Cooldown = (c.IsCanonicalDream ? 2.20f : 2.15f * cdScale), + DisplaySpeed = 95f, + SpreadRad = (c.IsCanonicalDream ? 0.005f : (0.008f + c.FdSpreadAdd) * spreadScale), + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.RefractingPrismLance: + { + float dmg = 58f * energyDmgScale; + float range = 310f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 450f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 34f, + MaxPenetrations = 1, + PenetrationDamageDecay = 0.65f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.16f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Refracting Prism-Lance {c.TierTag}", + SummaryLine1 = $"AUR LANCE | {dmg:F0} THERM PIERCE | {range:F0}m | 1x2", + SummaryLine2 = "Zero-recoil coherent prism beam pierces and superheats targets", + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + Root = root, + Height = 2, + ThermalMass = 11f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 92f, + PlateauWidth = 80f, + MaxTemp = 215f, + HeatOutput = 98f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.62f * cdScale, + DisplaySpeed = 450f, + SpreadRad = 0.003f * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.PulsedBeamSweeper: + { + float dmg = 18f * energyDmgScale; + int burst = Math.Clamp(2 + c.RxBurstAdd, 1, 4); + float range = 230f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 400f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 14f, + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + ColorRgba = c.ColorRgba, + TracerTtl = 0.12f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Pulsed Beam Sweeper {c.TierTag}", + SummaryLine1 = $"AUR SWEEPER | {dmg:F0}x{burst} LASER | {range:F0}m | 1x1", + SummaryLine2 = "Rapid-cycle optical emitter paints enemy radiators with thermal shear", + VisualClass = WeaponVisualClass.ThermalBeam, + AudioClass = OrdnanceAudioClass.LaserHeavy, + Root = root, + Height = 1, + ThermalMass = 9f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 90f, + PlateauWidth = 85f, + MaxTemp = 210f, + HeatOutput = 66f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.24f * cdScale, + DisplaySpeed = 400f, + SpreadRad = 0.008f * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.ThermalOverloadOrb: + { + float dmg = 38f * energyDmgScale; + float splash = 32f * energyDmgScale; + float range = 240f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 95f * velScale, + GravityScale = 0.08f, + MaxLifetime = 3.2f, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 6.0f, + HeatTransfer = 65f, + ScorchRadius = 4.0f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Pool, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.25f, + MaxPulses = 12, + RadialHeat = 12f, + RadialDamage = 4f, + RadialRadius = 8.0f + }, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 3.2f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Thermal Overload Orb {c.TierTag}", + SummaryLine1 = $"AUR ORB | {dmg + splash:F0} + HEAT RADIATION | 95m/s | 1x1", + SummaryLine2 = "Slow incandescent star-orb cooks nearby rigs in flight & spikes on hit", + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + Root = root, + Height = 1, + ThermalMass = 11f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 92f, + PlateauWidth = 80f, + MaxTemp = 215f, + HeatOutput = 105f * heatScale, + DirectSummaryDmg = dmg + splash, + Range = range, + Cooldown = 1.05f * cdScale, + DisplaySpeed = 95f * velScale, + SpreadRad = 0.008f * spreadScale, + BurstCount = 1 + }; + } + + // ---- VEX-NINE COLLECTIVE (12..15) ---- + case WeaponArchetypeKind.HomingSwarmPod: + { + float dmg = 26f * baseDmgScale; + float splash = 18f * baseDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 2, 5); + float range = 270f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HomingMissile, + LaunchPitchBiasDeg = 12f, + InitialSpeed = 62f * velScale, + ThrustAccel = 125f, + BurnTime = 2.0f, + MaxSpeed = 165f * velScale, + TurnRateRad = 4.8f, + SeekerConeDeg = 110f, + SeekerRange = range, + InterceptHp = 18f, + MaxLifetime = 3.2f, + Range = range, + DirectDamage = dmg, + SplashDamage = splash, + SplashRadius = 4.0f, + CraterRadius = 2.0f, + CraterDepth = 0.35f, + ScorchRadius = 2.5f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 3.2f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Homing Swarm Pod {c.TierTag}", + SummaryLine1 = $"VEX SWARM | {dmg + splash:F0}x{burst} SEEKER | 165m/s | 1x2", + SummaryLine2 = "Micro-seeker volley curves around ridge cover into locked hulls", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 12f, + OptimalTemp = 80f, + PlateauWidth = 85f, + MaxTemp = 195f, + HeatOutput = 82f * heatScale, + DirectSummaryDmg = dmg + splash * 0.6f, + Range = range, + Cooldown = 1.15f * cdScale, + DisplaySpeed = 165f * velScale, + SpreadRad = (0.065f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.AirburstProximitySwarm: + { + int splitCount = Math.Clamp(5 + c.FdSplitAdd, 4, 9); + float dartDmg = 20f * baseDmgScale; + float range = 270f * c.RxRangeMult; + var dart = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HomingMissile, + InitialSpeed = 85f, + ThrustAccel = 110f, + BurnTime = 1.4f, + MaxSpeed = 175f, + TurnRateRad = 5.4f, + SeekerConeDeg = 125f, + SeekerRange = 90f, + MaxLifetime = 2.0f, + DirectDamage = dartDmg, + SplashDamage = 14f * baseDmgScale, + SplashRadius = 3.4f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.RocketBoosted, + InitialSpeed = 95f * velScale, + ThrustAccel = 140f, + BurnTime = 1.2f, + MaxSpeed = 210f * velScale, + ProximityRadius = 15f, + ProximityIgnoreOwner = true, + MaxLifetime = 2.5f, + Range = range, + DirectDamage = 28f * baseDmgScale, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Rocket, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Proximity, Threshold = 15f, MinAge = 0.15f, Action = OrdnanceTriggerAction.Split, ChildNode = dart, SplitCount = splitCount, SplitConeDeg = 55f }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 2.5f, Action = OrdnanceTriggerAction.Split, ChildNode = dart, SplitCount = splitCount, SplitConeDeg = 55f } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Proximity Swarm Carrier {c.TierTag}", + SummaryLine1 = $"VEX AIRBURST | {splitCount}x{dartDmg:F0} DARTS | {range:F0}m | 1x2", + SummaryLine2 = $"Fuses 15m short of target to scatter {splitCount} homing micro-darts", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 12f, + OptimalTemp = 80f, + PlateauWidth = 85f, + MaxTemp = 195f, + HeatOutput = 88f * heatScale, + DirectSummaryDmg = dartDmg * splitCount * 0.55f, + Range = range, + Cooldown = 1.30f * cdScale, + DisplaySpeed = 210f * velScale, + SpreadRad = (0.020f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.SmartSpiderMineTrap: + { + float mineDmg = 36f * baseDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 2, 4); + float range = 175f * c.RxRangeMult; + var mine = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + ArmDelay = 0.5f, + ProximityRadius = 6.0f, + ProximityIgnoreOwner = true, + MaxLifetime = 26f, + InterceptHp = 16f, + SplashDamage = mineDmg, + SplashRadius = 6.0f, + HeatTransfer = 16f, + CraterRadius = 2.0f, + CraterDepth = 0.4f, + ScorchRadius = 2.6f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Proximity, Threshold = 6.0f, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 26f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 18f, + InitialSpeed = 58f, + GravityScale = 1.15f, + MaxLifetime = 4.0f, + Range = range, + DirectDamage = 14f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Mine, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = mine }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Spider-Mine Trap {c.TierTag}", + SummaryLine1 = $"VEX MINES | {burst}x{mineDmg:F0} SMART TRAP | {range:F0}m | 1x1", + SummaryLine2 = "Deploys IFF-safe spider mines that ignore owner & ambush pursuers", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.RocketSalvo, + Root = root, + Height = 1, + ThermalMass = 10f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 12f, + OptimalTemp = 80f, + PlateauWidth = 85f, + MaxTemp = 195f, + HeatOutput = 72f * heatScale, + DirectSummaryDmg = mineDmg, + Range = range, + Cooldown = 1.20f * cdScale, + DisplaySpeed = 58f, + SpreadRad = (0.09f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + case WeaponArchetypeKind.PointDefenseWeb: + { + float dmg = 15f * energyDmgScale; + int burst = Math.Clamp(3 + c.RxBurstAdd, 2, 5); + float range = 205f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 420f * velScale, + Range = range, + DirectDamage = dmg, + IsAirburst = true, + HeatTransfer = 6f, + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.CannonLight, + ColorRgba = c.ColorRgba, + TracerTtl = 0.09f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Aegis PD-Web {c.TierTag}", + SummaryLine1 = $"VEX WIDE-PD | {dmg:F0}x{burst} +85deg AUTO | {range:F0}m | 1x1", + SummaryLine2 = "Wide-arc automated interceptor web tracks VTOLs & loitering drones", + VisualClass = WeaponVisualClass.SwarmSmart, + AudioClass = OrdnanceAudioClass.CannonLight, + Root = root, + Height = 1, + ThermalMass = 9f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 85f, + PlateauWidth = 90f, + MaxTemp = 210f, + HeatOutput = 30f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.18f * cdScale, + DisplaySpeed = 420f * velScale, + SpreadRad = (0.022f + c.FdSpreadAdd) * spreadScale, + BurstCount = burst + }; + } + + // ---- THALASSAN FORGE (16..19) ---- + case WeaponArchetypeKind.HypervelocityGaussRail: + { + float dmg = 96f * baseDmgScale; + float speed = 420f * velScale; + float range = 380f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = speed, + GravityScale = 0.02f, + MaxLifetime = 1.2f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 18f, + MaxPenetrations = 2, + PenetrationDamageDecay = 0.75f, + CraterRadius = 2.4f, + CraterDepth = 0.45f, + ScorchRadius = 2.8f, + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + ColorRgba = c.ColorRgba, + TracerTtl = 0.15f, + VisualShape = OrdnanceVisualShape.SabotCarrier, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 1.2f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Gauss Rail-Driver {c.TierTag}", + SummaryLine1 = $"THL GAUSS | {dmg:F0}x3 PIERCE | {speed:F0}m/s | 1x2", + SummaryLine2 = "420m/s electromagnetic slug over-penetrates through 2 armored hulls", + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + Root = root, + Height = 2, + ThermalMass = 14f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 92f, + PlateauWidth = 70f, + MaxTemp = 210f, + HeatOutput = 135f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 1.35f * cdScale, + DisplaySpeed = speed, + SpreadRad = 0.004f * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.PlasmaPoolMortar: + { + float impactSplash = 36f * energyDmgScale; + float poolTickDmg = 12f * energyDmgScale; + float range = 240f * c.RxRangeMult; + var pool = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.StationaryMine, + ArmDelay = 0f, + IsThermalPool = true, + MaxLifetime = 6.0f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Pool, + WhileAlive = new OrdnanceWhileAliveDef + { + Interval = 0.5f, + MaxPulses = 12, + RadialDamage = poolTickDmg, + RadialHeat = 22f, + RadialRadius = 6.5f + }, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 6.0f, Action = OrdnanceTriggerAction.Fizzle } } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + LaunchPitchBiasDeg = 22f, + InitialSpeed = 82f * velScale, + GravityScale = 1.1f, + MaxLifetime = 4.0f, + Range = range, + DirectDamage = 28f * energyDmgScale, + SplashDamage = impactSplash, + SplashRadius = 5.5f, + HeatTransfer = 35f, + ScorchRadius = 6.2f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + VisualShape = OrdnanceVisualShape.Pool, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = pool }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 4.0f, Action = OrdnanceTriggerAction.Detonate } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Plasma Pool Mortar {c.TierTag}", + SummaryLine1 = $"THL PLASMA | {impactSplash:F0} + 6s SCORCH POOL | 1x2", + SummaryLine2 = "Ignites a 6.5m scorching plasma puddle roasting chassis treads", + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + Root = root, + Height = 2, + ThermalMass = 13f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 14f, + OptimalTemp = 95f, + PlateauWidth = 75f, + MaxTemp = 215f, + HeatOutput = 115f * heatScale, + DirectSummaryDmg = impactSplash + poolTickDmg * 4f, + Range = range, + Cooldown = 1.35f * cdScale, + DisplaySpeed = 82f * velScale, + SpreadRad = (0.016f + c.FdSpreadAdd) * spreadScale, + BurstCount = 1 + }; + } + + case WeaponArchetypeKind.ArcDischargeLance: + { + float dmg = 42f * energyDmgScale; + float arcDmg = 18f * energyDmgScale; + float range = 250f * c.RxRangeMult; + var arcBolt = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + InitialSpeed = 180f, + GravityScale = 0f, + MaxLifetime = 0.22f, + DirectDamage = arcDmg, + HeatTransfer = 18f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + TracerTtl = 0.12f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate }, + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Timeout, Threshold = 0.22f, Action = OrdnanceTriggerAction.Fizzle } + } + }; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 420f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 28f, + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + ColorRgba = c.ColorRgba, + TracerTtl = 0.14f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Split, ChildNode = arcBolt, SplitCount = 3, SplitConeDeg = 75f } + } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Arc Discharge Lance {c.TierTag}", + SummaryLine1 = $"THL ARC | {dmg:F0} + 3x{arcDmg:F0} CHAIN | {range:F0}m | 1x2", + SummaryLine2 = "Primary lightning beam forks 3 secondary plasma arcs off hit surface", + VisualClass = WeaponVisualClass.PlasmaPpc, + AudioClass = OrdnanceAudioClass.PlasmaPpc, + Root = root, + Height = 2, + ThermalMass = 12f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 92f, + PlateauWidth = 75f, + MaxTemp = 215f, + HeatOutput = 92f * heatScale, + DirectSummaryDmg = dmg + arcDmg * 1.5f, + Range = range, + Cooldown = 0.72f * cdScale, + DisplaySpeed = 420f, + SpreadRad = 0.008f * spreadScale, + BurstCount = 1 + }; + } + + default: // RailPlasmaBeam + { + float dmg = 68f * energyDmgScale; + float range = 320f * c.RxRangeMult; + var root = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.HitscanBeam, + InitialSpeed = 460f, + Range = range, + DirectDamage = dmg, + HeatTransfer = 44f, + MaxPenetrations = 2, + PenetrationDamageDecay = 0.72f, + ScorchRadius = 2.6f, + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + ColorRgba = c.ColorRgba, + TracerTtl = 0.16f, + VisualShape = OrdnanceVisualShape.Bolt, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Detonate } } + }; + return new BuiltArchetype + { + DisplayName = $"{c.Prefix} Rail-Plasma Beam {c.TierTag}", + SummaryLine1 = $"THL RAIL-PPC | {dmg:F0} PIERCE+HEAT | {range:F0}m | 1x2", + SummaryLine2 = "Superheated magnetic particle beam punches multiple targets & spikes heat", + VisualClass = WeaponVisualClass.GaussRail, + AudioClass = OrdnanceAudioClass.GaussRail, + Root = root, + Height = 2, + ThermalMass = 14f + c.RxThermalMassAdd + c.FdThermalMassAdd, + Conductivity = 15f, + OptimalTemp = 95f, + PlateauWidth = 70f, + MaxTemp = 220f, + HeatOutput = 118f * heatScale, + DirectSummaryDmg = dmg, + Range = range, + Cooldown = 0.88f * cdScale, + DisplaySpeed = 460f, + SpreadRad = 0.004f * spreadScale, + BurstCount = 1 + }; + } + } + } + + private static float ComputePowerScore(OrdnanceNodeDef root, int burstCount, float cooldown, float summaryDmg) + { + float effectivePerShot = MathF.Max(summaryDmg, root.DirectDamage + root.SplashDamage * 0.8f); + float dps = (effectivePerShot * MathF.Max(1, burstCount)) / MathF.Max(0.15f, cooldown); + float complexityBonus = 1f; + if (root.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile or OrdnanceMotion.LoiterOrbit) + { + complexityBonus += 0.25f; + } + if (root.Triggers.Length > 1 || root.WhileAlive is not null || root.MaxPenetrations > 0) + { + complexityBonus += 0.35f; + } + return dps * complexityBonus; + } + + private static ulong Mix64(ulong x) + { + x += 0x9E3779B97F4A7C15UL; + x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9UL; + x = (x ^ (x >> 27)) * 0x94D049BB133111EBUL; + return x ^ (x >> 31); + } + + private static ulong NextU64(ref ulong state) + { + state = Mix64(state); + return state; + } + + private static float NextFloat(ref ulong state) => + (NextU64(ref state) & 0xFFFFFFUL) / (float)0x1000000UL; + + private static float Lerp(float a, float b, float t) => a + (b - a) * t; + } +} diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs index 7d2b9f2..9e70a6c 100644 --- a/src/RustToDust.Core/SimEvents.cs +++ b/src/RustToDust.Core/SimEvents.cs @@ -32,11 +32,34 @@ namespace RustToDust.Core [Union(10, typeof(OverheatAlertEvent))] [Union(11, typeof(MatchResetEvent))] [Union(12, typeof(DropPodEvent))] - // Reserved [Union(13)] OrdnanceNodeEvent (Cut 7) + [Union(13, typeof(OrdnanceNodeEvent))] public interface ISimEvent { } + [MessagePackObject] + public sealed class OrdnanceNodeEvent : ISimEvent + { + [Key(0)] public int OrdnanceId { get; set; } + [Key(1)] public int ParentOrdnanceId { get; set; } + [Key(2)] public byte Kind { get; set; } + [Key(3)] public bool IsSpectatorShooter { get; set; } + [Key(4)] public int ShooterId { get; set; } + [Key(5)] public ProceduralWeaponKey? WeaponKey { get; set; } + [Key(6)] public byte NodeDefIndex { get; set; } + [Key(7)] public float PosX { get; set; } + [Key(8)] public float PosY { get; set; } + [Key(9)] public float PosZ { get; set; } + [Key(10)] public float VelX { get; set; } + [Key(11)] public float VelY { get; set; } + [Key(12)] public float VelZ { get; set; } + [Key(13)] public int TargetEntityId { get; set; } = -1; + [Key(14)] public bool TargetIsSpectator { get; set; } + [Key(15)] public float SimTime { get; set; } + [Key(16)] public byte VisualShape { get; set; } + [Key(17)] public uint ColorRgba { get; set; } + } + public enum DropPodEventKind : byte { WaveAnnounced = 0, diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs index 788cdb4..e484752 100644 --- a/src/RustToDust.Core/SpectatorRing.cs +++ b/src/RustToDust.Core/SpectatorRing.cs @@ -787,13 +787,36 @@ namespace RustToDust.Core int count = rng.Next(1, 3); for (int i = 0; i < count; i++) { - drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); + if (rng.NextDouble() < 0.55) + { + ManufacturerId mfg = (rng.Next(3)) switch + { + 0 => ManufacturerId.AuralianOptics, + 1 => ManufacturerId.ThalassanForge, + _ => ManufacturerId.VexNineCollective + }; + ulong seed = ((ulong)(uint)spec.Id << 32) ^ (uint)rng.Next(); + drops.Add(ProceduralWeaponGenerator.RollForManufacturer(mfg, tier: rng.Next(2, 4), seed).Module); + } + else + { + drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); + } } break; } case SpectatorTier.Patron: { - if (rng.NextDouble() < 0.5) + double roll = rng.NextDouble(); + if (roll < 0.4) + { + ManufacturerId mfg = rng.Next(2) == 0 + ? ManufacturerId.KorrathiIronworks + : ManufacturerId.VexNineCollective; + ulong seed = ((ulong)(uint)spec.Id << 32) ^ (uint)rng.Next(); + drops.Add(ProceduralWeaponGenerator.RollForManufacturer(mfg, tier: rng.Next(1, 3), seed).Module); + } + else if (roll < 0.65) { drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); } diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index d62693e..f825cc9 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -752,7 +752,7 @@ namespace RustToDust.Net gd.X, gd.Z, gd.ChassisId is not null && Catalog.ChassisById.TryGetValue(gd.ChassisId, out var cs) ? cs : null, - gd.ModuleId is not null && Catalog.ModulesById.TryGetValue(gd.ModuleId, out var ms) ? ms : null); + Catalog.TryGetModule(gd.ModuleId, out var ms) ? ms : null); d.PickedUp = gd.PickedUp; } @@ -814,7 +814,7 @@ namespace RustToDust.Net for (int m = 0; m < sd.Mounted.Count; m++) mounted.Add((sd.Mounted[m].ModuleId, sd.Mounted[m].HardpointId)); if (Catalog.TryGetChassisSpecOrExemplar(sd.ChassisId, out var spec)) { - s.Grid.ApplyReplicatedLoadout(spec, sd.CoreHp, sd.MaxCoreHp, sd.ArmorBytes, mounted, null, id => Catalog.ModulesById.TryGetValue(id, out var ms) ? ms : null); + s.Grid.ApplyReplicatedLoadout(spec, sd.CoreHp, sd.MaxCoreHp, sd.ArmorBytes, mounted, null, id => Catalog.TryGetModule(id, out var ms) ? ms : null); } _spectatorTimeline[sIdx].Clear(); _spectatorVisible[sIdx] = true; @@ -1514,7 +1514,7 @@ namespace RustToDust.Net _viewState.ApplyReplicatedDropSpawned( ds.DropId, ds.X, ds.Z, ds.ChassisId is not null && Catalog.ChassisById.TryGetValue(ds.ChassisId, out var cs) ? cs : null, - ds.ModuleId is not null && Catalog.ModulesById.TryGetValue(ds.ModuleId, out var ms) ? ms : null); + Catalog.TryGetModule(ds.ModuleId, out var ms) ? ms : null); break; case DropPickedUpEvent dp: _viewState.ApplyReplicatedDropPickedUp(dp.DropId); @@ -1578,6 +1578,9 @@ namespace RustToDust.Net case DropPodEvent dpe: _viewState.OrbitalDrop.ApplyReplicatedDropPodEvent(dpe, QueryLocalDropSurface); break; + case OrdnanceNodeEvent: + // Forwarded to _pendingClientEvents; ClientOrdnanceMirror attaches in Cut 7b + break; case SpectatorDestroyedEvent sdet: { int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId; @@ -1691,7 +1694,7 @@ namespace RustToDust.Net cl.ArmorBytes, mounted, cl.CargoIds, - id => Catalog.ModulesById.TryGetValue(id, out var ms) ? ms : null); + id => Catalog.TryGetModule(id, out var ms) ? ms : null); } private static void PushPoseSample(List timeline, float simTime, Vector3 pos, Quaternion rot, Vector3 vel) diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index bebe38e..40211e0 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -31,6 +31,7 @@ namespace RustToDust.Net public readonly EntityPvsTracker[] SpectatorTrackers = new EntityPvsTracker[SpectatorRing.DefaultSpectatorCount]; public readonly HashSet SentDropIds = new(); public readonly HashSet SentPodIds = new(); + public readonly HashSet SentOrdnanceIds = new(); } private struct EntityPvsTracker @@ -573,6 +574,7 @@ namespace RustToDust.Net } } peer.SentPodIds.Clear(); + peer.SentOrdnanceIds.Clear(); var activePods = _session.State.OrbitalDrop.ActivePods; for (int i = 0; i < activePods.Count; i++) { @@ -828,6 +830,29 @@ namespace RustToDust.Net } break; } + case OrdnanceNodeEvent ord: + { + bool shooterInPvs = ord.IsSpectatorShooter + ? (ord.ShooterId >= 0 && _session.IsEntityInPeerPvs(obsId, false, ord.ShooterId)) + : (ord.ShooterId == obsId || (ord.ShooterId >= 0 && _session.IsEntityInPeerPvs(obsId, true, ord.ShooterId))); + bool pointInPvs = _session.IsPointInPeerPvs(obsId, ord.PosX, ord.PosY + 0.35f, ord.PosZ); + byte kind = ord.Kind; + bool isTerminal = kind is 3 or 4 or 5; // Detonated, Intercepted, Expired + if (isTerminal) + { + bool wasSent = peer.SentOrdnanceIds.Remove(ord.OrdnanceId); + if (wasSent || shooterInPvs || pointInPvs) + { + filtered.Add(ord); + } + } + else if (shooterInPvs || pointInPvs) + { + peer.SentOrdnanceIds.Add(ord.OrdnanceId); + filtered.Add(ord); + } + break; + } default: filtered.Add(ev); break; diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 42e2bc4..9783dc0 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -7,7 +7,7 @@ using Ymir.Box3D; namespace RustToDust.Ymir { - public sealed class ArenaSession : IDisposable + public sealed class ArenaSession : IDisposable, IOrdnanceTargetSink { public const float FixedDt = 1f / 60f; public const int SubStepCount = 4; @@ -31,12 +31,14 @@ namespace RustToDust.Ymir private readonly bool[,] _contenderPvs = new bool[MatchState.ContenderCount, MatchState.ContenderCount]; private readonly bool[,] _spectatorPvs; private readonly List _stepEvents = new(); + private readonly List _ordnanceNetScratch = new(64); private long _forwardedPodEventId; private bool _disposed; public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false) { State = new MatchState(seed, mapKind, skipInitialDrop); + Ordnance = new OrdnanceRuntime(this); _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; @@ -87,6 +89,7 @@ namespace RustToDust.Ymir public static double PerfWeaponsMs; public MatchState State { get; } + public OrdnanceRuntime Ordnance { get; } public Box3DSoaWorld World => _world; public bool EnableNetworkPvs { get; set; } = true; @@ -2274,6 +2277,35 @@ namespace RustToDust.Ymir extraSpread: s.AimSpreadRad + s.DynamicAimSpreadRad, view: view); } + + Ordnance.Step(FixedDt); + _ordnanceNetScratch.Clear(); + Ordnance.DrainNetEvents(_ordnanceNetScratch); + for (int i = 0; i < _ordnanceNetScratch.Count; i++) + { + var ev = _ordnanceNetScratch[i]; + _stepEvents.Add(new OrdnanceNodeEvent + { + OrdnanceId = ev.OrdnanceId, + ParentOrdnanceId = ev.ParentOrdnanceId, + Kind = (byte)ev.Kind, + IsSpectatorShooter = ev.IsSpectatorShooter, + ShooterId = ev.ShooterEntityId, + WeaponKey = ev.WeaponKey, + NodeDefIndex = ev.NodeDefIndex, + PosX = ev.Pos.X, + PosY = ev.Pos.Y, + PosZ = ev.Pos.Z, + VelX = ev.Vel.X, + VelY = ev.Vel.Y, + VelZ = ev.Vel.Z, + TargetEntityId = ev.TargetEntityId, + TargetIsSpectator = ev.TargetIsSpectator, + SimTime = ev.SimTime, + VisualShape = ev.VisualShape, + ColorRgba = ev.ColorRgba + }); + } } private void UpdateWeaponArcTelemetry(ContenderState c, Quaternion shooterQuat, ulong shooterStableId) @@ -2402,27 +2434,55 @@ namespace RustToDust.Ymir bestVtol = other; } - if (bestVtol is null) + if (bestVtol is not null) { - continue; + float aimY = MatchRules.GetTargetAimY(bestVtol.Y, bestVtol.Grid.Spec.HalfHeight); + FireSingleWeapon( + mod, + shooterStableId, + shooter, + shooter.Name, + isSpectatorShooter: false, + shooter.Grid, + shooterPos, + shooter.Yaw, + shooterQuat, + bestVtol.X, + aimY, + bestVtol.Z, + extraSpread: 0f, + view: view); + } + else + { + Vector3 pdMuzzle = ComputeWeaponMuzzle(shooterPos, shooter.Yaw, shooter.Grid.Spec, shooterPos.X, shooterPos.Z + 10f); + if (Ordnance.TryFindBestHostileAirborneOrdnance( + pdMuzzle, + shooterStableId, + shooterQuat, + minPitch, + maxPitch, + range, + out _, + out Vector3 ordPos)) + { + FireSingleWeapon( + mod, + shooterStableId, + shooter, + shooter.Name, + isSpectatorShooter: false, + shooter.Grid, + shooterPos, + shooter.Yaw, + shooterQuat, + ordPos.X, + ordPos.Y, + ordPos.Z, + extraSpread: 0f, + view: view); + } } - - float aimY = MatchRules.GetTargetAimY(bestVtol.Y, bestVtol.Grid.Spec.HalfHeight); - FireSingleWeapon( - mod, - shooterStableId, - shooter, - shooter.Name, - isSpectatorShooter: false, - shooter.Grid, - shooterPos, - shooter.Yaw, - shooterQuat, - bestVtol.X, - aimY, - bestVtol.Z, - extraSpread: 0f, - view: view); } } @@ -2539,246 +2599,29 @@ namespace RustToDust.Ymir ? Vector3.UnitZ : Vector3.Normalize(aimDelta); - int burst = Math.Max(1, mod.Spec.BurstCount); float totalSpread = mod.Spec.SpreadRad + extraSpread; - float range = MathF.Max(5f, mod.Spec.WeaponRange); - WeaponVisualClass weaponClass = MatchState.ClassifyWeaponVisual(mod.Spec.Id); - uint tracerColor = weaponClass switch - { - WeaponVisualClass.ThermalBeam => string.Equals(mod.Spec.Id, "gilded_lance", StringComparison.Ordinal) - ? 0xFFD966FFu - : 0x5CE6FFFFu, - WeaponVisualClass.Explosive => 0xFF6622FFu, - WeaponVisualClass.Autocannon => 0xFF9933FFu, - _ => string.Equals(mod.Spec.Id, "pd_flak", StringComparison.Ordinal) - ? 0xFF8833FFu - : 0xFFE888FFu - }; - float tracerTtl = weaponClass switch - { - WeaponVisualClass.ThermalBeam => 0.13f, - WeaponVisualClass.Explosive => 0.12f, - WeaponVisualClass.Autocannon => 0.10f, - _ => 0.09f - }; - bool isPdFlak = string.Equals(mod.Spec.Id, "pd_flak", StringComparison.Ordinal); + float aimDist = aimDelta.Length(); + OrdnanceNodeDef rootDef = OrdnanceCatalogMapper.ResolveRoot(mod.Spec); + ulong targetStableId = ResolveTargetEntityStableId(aimX, targetY, aimZ, shooterStableId); + int shooterEntityId = isSpectatorShooter + ? (int)(shooterStableId - SpectatorStableIdBase) + : (shooterContender?.Id ?? -1); - for (int b = 0; b < burst; b++) - { - float yawJitter = ((float)State.Rng.NextDouble() * 2f - 1f) * totalSpread; - float pitchJitter = ((float)State.Rng.NextDouble() * 2f - 1f) * (totalSpread * 0.35f); - var dir = ApplyAimSpread(baseAim, yawJitter, pitchJitter); - - Vector3 castOrigin = muzzle; - float remainingRange = range; - bool hitAny = false; - ulong hitStableId = 0; - (float X, float Y, float Z) hitPoint = default; - for (int hop = 0; hop < 4 && remainingRange > 0.2f; hop++) - { - var rayHit = _world.CastRayClosest( - (castOrigin.X, castOrigin.Y, castOrigin.Z), - (dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange)); - if (!rayHit.Hit) - { - break; - } - if (rayHit.StableId != shooterStableId) - { - hitAny = true; - hitStableId = rayHit.StableId; - hitPoint = rayHit.Point; - break; - } - - var selfPt = new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z); - float skip = MathF.Max(0.15f, Vector3.Distance(castOrigin, selfPt) + 0.08f); - castOrigin += dir * skip; - remainingRange = MathF.Max(0f, remainingRange - skip); - } - - float boxDist = hitAny - ? Vector3.Distance(muzzle, new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z)) - : range; - - bool hitTerrain = State.Terrain.Raycast( - muzzle.X, muzzle.Y, muzzle.Z, - dir.X, dir.Y, dir.Z, - boxDist, - out float tx, out float ty, out float tz, out float terrainDist); - - Vector3 endPt; - int shooterEntityId = isSpectatorShooter - ? (int)(shooterStableId - SpectatorStableIdBase) - : (shooterContender?.Id ?? -1); - if (hitTerrain && terrainDist < boxDist) - { - endPt = new Vector3(tx, ty, tz); - StampTerrainWeaponImpact(mod.Spec.Id, tx, tz, burstIndex: b); - var (tnx, tny, tnz) = State.Terrain.SampleNormal(tx, tz); - long hitId = State.AllocateHitEventId(); - State.HitEvents.Add(new HitFeedbackEvent( - EventId: hitId, - HitX: tx, - HitY: ty, - HitZ: tz, - NormalX: tnx, - NormalY: tny, - NormalZ: tnz, - SourceX: shooterPos.X, - SourceY: shooterPos.Y, - SourceZ: shooterPos.Z, - TargetKind: HitTargetKind.Terrain, - TargetId: -1, - CellX: 0, - CellY: 0, - WeaponClass: weaponClass, - WeaponId: mod.Spec.Id, - IsAirburst: false, - Ttl: 0.35f)); - _stepEvents.Add(new HitImpactEvent - { - EventId = hitId, - HitX = tx, HitY = ty, HitZ = tz, - NormalX = tnx, NormalY = tny, NormalZ = tnz, - SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, - TargetKind = (byte)HitTargetKind.Terrain, - TargetId = -1, - WeaponClass = (byte)weaponClass, - WeaponId = mod.Spec.Id, - Ttl = 0.35f, - ShooterId = shooterEntityId, - IsContenderShooter = !isSpectatorShooter - }); - } - else - { - endPt = hitAny - ? new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) - : muzzle + dir * range; - - if (hitAny && hitStableId != shooterStableId && _entityByStableId.TryGetValue(hitStableId, out var targetRef)) - { - ApplyHitToTarget( - targetRef, - hitPoint, - dir, - shooterPos, - weaponClass, - mod.Spec.Id, - isPdFlak, - mod.Spec.WeaponDamage * mod.CurrentPerformance, - mod.Spec.HeatOutput * 0.25f, - shooterContender, - shooterLabel, - isSpectatorShooter, - shooterEntityId, - view); - } - else if (hitAny && hitStableId != shooterStableId) - { - // Static cover box hit - Vector3 rev = -dir; - long hitId = State.AllocateHitEventId(); - State.HitEvents.Add(new HitFeedbackEvent( - EventId: hitId, - HitX: endPt.X, - HitY: endPt.Y, - HitZ: endPt.Z, - NormalX: rev.X, - NormalY: rev.Y, - NormalZ: rev.Z, - SourceX: shooterPos.X, - SourceY: shooterPos.Y, - SourceZ: shooterPos.Z, - TargetKind: HitTargetKind.StaticCover, - TargetId: (int)hitStableId, - CellX: 0, - CellY: 0, - WeaponClass: weaponClass, - WeaponId: mod.Spec.Id, - IsAirburst: isPdFlak, - Ttl: 0.35f)); - _stepEvents.Add(new HitImpactEvent - { - EventId = hitId, - HitX = endPt.X, HitY = endPt.Y, HitZ = endPt.Z, - NormalX = rev.X, NormalY = rev.Y, NormalZ = rev.Z, - SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, - TargetKind = (byte)HitTargetKind.StaticCover, - TargetId = (int)hitStableId, - WeaponClass = (byte)weaponClass, - WeaponId = mod.Spec.Id, - IsAirburst = isPdFlak, - Ttl = 0.35f, - ShooterId = shooterEntityId, - IsContenderShooter = !isSpectatorShooter - }); - } - else if (isPdFlak && b == 0) - { - Vector3 airPt = muzzle + dir * MathF.Min(range, MathF.Max(20f, aimDelta.Length())); - Vector3 rev = -dir; - long hitId = State.AllocateHitEventId(); - State.HitEvents.Add(new HitFeedbackEvent( - EventId: hitId, - HitX: airPt.X, - HitY: airPt.Y, - HitZ: airPt.Z, - NormalX: rev.X, - NormalY: rev.Y, - NormalZ: rev.Z, - SourceX: shooterPos.X, - SourceY: shooterPos.Y, - SourceZ: shooterPos.Z, - TargetKind: HitTargetKind.StaticCover, - TargetId: -1, - CellX: 0, - CellY: 0, - WeaponClass: weaponClass, - WeaponId: mod.Spec.Id, - IsAirburst: true, - Ttl: 0.35f)); - _stepEvents.Add(new HitImpactEvent - { - EventId = hitId, - HitX = airPt.X, HitY = airPt.Y, HitZ = airPt.Z, - NormalX = rev.X, NormalY = rev.Y, NormalZ = rev.Z, - SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, - TargetKind = (byte)HitTargetKind.StaticCover, - TargetId = -1, - WeaponClass = (byte)weaponClass, - WeaponId = mod.Spec.Id, - IsAirburst = true, - Ttl = 0.35f, - ShooterId = shooterEntityId, - IsContenderShooter = !isSpectatorShooter - }); - } - } - - int tracerId = State.AllocateTracerId(); - State.Tracers.Add(new TracerEvent( - muzzle.X, muzzle.Y, muzzle.Z, - endPt.X, endPt.Y, endPt.Z, - tracerColor, - tracerTtl, - weaponClass, - mod.Spec.Id, - tracerId)); - _stepEvents.Add(new ShotFiredEvent - { - TracerId = tracerId, - IsSpectatorShooter = isSpectatorShooter, - ShooterId = shooterEntityId, - StartX = muzzle.X, StartY = muzzle.Y, StartZ = muzzle.Z, - EndX = endPt.X, EndY = endPt.Y, EndZ = endPt.Z, - ColorRgba = tracerColor, - Ttl = tracerTtl, - WeaponClass = (byte)weaponClass, - WeaponId = mod.Spec.Id - }); - } + Ordnance.FireWeapon(new OrdnanceFireRequest( + Module: mod, + ShooterStableId: shooterStableId, + ShooterContender: shooterContender, + ShooterLabel: shooterLabel, + IsSpectatorShooter: isSpectatorShooter, + ShooterEntityId: shooterEntityId, + ShooterPos: shooterPos, + MuzzlePos: muzzle, + AimDir: baseAim, + AimDist: aimDist, + SpreadRad: totalSpread, + TargetEntityStableId: targetStableId, + RootDef: rootDef, + WeaponKey: mod.Spec.Procedural?.Key)); shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput); mod.Cooldown = mod.Spec.FireCooldown; @@ -2787,7 +2630,8 @@ namespace RustToDust.Ymir { bool isContenderShooter = !isSpectatorShooter; int entityId = (int)(shooterStableId - (isContenderShooter ? ContenderStableIdBase : SpectatorStableIdBase)); - AddWalkerRecoilImpulse(isContenderShooter, entityId, baseAim, mod.Spec.WeaponDamage); + float recoilScale = mod.Spec.Procedural?.RecoilMultiplier ?? 1f; + AddWalkerRecoilImpulse(isContenderShooter, entityId, baseAim, mod.Spec.WeaponDamage * recoilScale); } if (shooterContender is not null) @@ -2798,6 +2642,61 @@ namespace RustToDust.Ymir } } + private ulong ResolveTargetEntityStableId(float aimX, float aimY, float aimZ, ulong shooterStableId) + { + const float maxLockRadiusSq = 10f * 10f; + float bestDistSq = maxLockRadiusSq; + ulong bestId = 0; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong stable = ContenderStableIdBase + (ulong)c.Id; + if (stable == shooterStableId) + { + continue; + } + float dx = c.X - aimX; + float dy = c.Y - aimY; + float dz = c.Z - aimZ; + float d2 = dx * dx + dy * dy + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestId = stable; + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) + { + continue; + } + ulong stable = SpectatorStableIdBase + (ulong)s.Id; + if (stable == shooterStableId) + { + continue; + } + float dx = s.X - aimX; + float dy = s.Y - aimY; + float dz = s.Z - aimZ; + float d2 = dx * dx + dy * dy + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestId = stable; + } + } + + return bestId; + } + private void ApplyHitToTarget( (bool IsContender, int Index) targetRef, (float X, float Y, float Z) hitPoint, @@ -3058,23 +2957,276 @@ namespace RustToDust.Ymir State.Broadcast.EmitElimination(State.Time, shooterLabel, $"{spec.Tier} Spectator", false); } - private void StampTerrainWeaponImpact(string weaponId, float x, float z, int burstIndex) + bool IOrdnanceTargetSink.TryResolveActor(ulong stableId, out bool isContender, out int index) { - switch (weaponId) + if (_entityByStableId.TryGetValue(stableId, out var entry)) { - case "recoilless": - State.Terrain.StampCrater(x, z, radius: 4.2f, depth: 1.05f); - State.Terrain.StampScorch(x, z, radius: 4.5f); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = x, Z = z, Radius = 4.2f, Depth = 1.05f }); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = x, Z = z, Radius = 4.5f }); - break; - case "flak": - if (burstIndex == 0) - { - State.Terrain.StampCrater(x, z, radius: 2.0f, depth: 0.35f); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = x, Z = z, Radius = 2.0f, Depth = 0.35f }); - } - break; + isContender = entry.IsContender; + index = entry.Index; + return true; + } + isContender = false; + index = -1; + return false; + } + + Vector3 IOrdnanceTargetSink.GetActorAimPosition(bool isContender, int index) + { + if (isContender) + { + var c = State.Contenders[index]; + return new Vector3(c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z); + } + var s = State.Spectators.Spectators[index]; + return new Vector3(s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); + } + + void IOrdnanceTargetSink.ApplyDirectHit( + ulong targetStableId, + (float X, float Y, float Z) hitPoint, + Vector3 shotDir, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + float damage, + float heatTransfer, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId) + { + if (!_entityByStableId.TryGetValue(targetStableId, out var targetRef)) + { + return; + } + ApplyHitToTarget( + targetRef, + hitPoint, + shotDir, + shooterPos, + weaponClass, + weaponId, + isAirburst, + damage, + heatTransfer, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId, + _world.View); + } + + void IOrdnanceTargetSink.ApplySplashDamage( + Vector3 center, + float radius, + float splashDamage, + float heatTransfer, + WeaponVisualClass weaponClass, + string weaponId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + ulong ignoreStableId) + { + if (radius <= 0.1f || (splashDamage <= 0f && heatTransfer <= 0f)) + { + return; + } + + var view = _world.View; + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ContenderStableIdBase + (ulong)c.Id; + if (cStable == ignoreStableId) + { + continue; + } + + Vector3 cPos = new(c.X, c.Y, c.Z); + float bodyPad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength); + float rawDist = Vector3.Distance(center, cPos); + float effDist = MathF.Max(0f, rawDist - bodyPad); + if (effDist > radius) + { + continue; + } + + float atten = 1f - 0.55f * Math.Clamp(effDist / radius, 0f, 1f); + Vector3 shotDir = rawDist > 1e-4f ? Vector3.Normalize(cPos - center) : Vector3.UnitY; + Vector3 hitPt = cPos - shotDir * MathF.Min(rawDist, bodyPad * 0.7f); + ApplyHitToTarget( + (true, i), + (hitPt.X, hitPt.Y, hitPt.Z), + shotDir, + center, + weaponClass, + weaponId, + isPdFlak: false, + splashDamage * atten, + heatTransfer * atten, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId, + view); + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive) + { + continue; + } + ulong sStable = SpectatorStableIdBase + (ulong)s.Id; + if (sStable == ignoreStableId) + { + continue; + } + + Vector3 sPos = new(s.X, s.Y, s.Z); + float bodyPad = MathF.Max(s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfLength); + float rawDist = Vector3.Distance(center, sPos); + float effDist = MathF.Max(0f, rawDist - bodyPad); + if (effDist > radius) + { + continue; + } + + float atten = 1f - 0.55f * Math.Clamp(effDist / radius, 0f, 1f); + Vector3 shotDir = rawDist > 1e-4f ? Vector3.Normalize(sPos - center) : Vector3.UnitY; + Vector3 hitPt = sPos - shotDir * MathF.Min(rawDist, bodyPad * 0.7f); + ApplyHitToTarget( + (false, i), + (hitPt.X, hitPt.Y, hitPt.Z), + shotDir, + center, + weaponClass, + weaponId, + isPdFlak: false, + splashDamage * atten, + heatTransfer * atten, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId, + view); + } + } + + void IOrdnanceTargetSink.EmitTracer( + Vector3 start, + Vector3 end, + uint colorRgba, + float ttl, + WeaponVisualClass weaponClass, + string weaponId, + bool isSpectatorShooter, + int shooterEntityId) + { + int tracerId = State.AllocateTracerId(); + State.Tracers.Add(new TracerEvent( + start.X, start.Y, start.Z, + end.X, end.Y, end.Z, + colorRgba, + ttl, + weaponClass, + weaponId, + tracerId)); + _stepEvents.Add(new ShotFiredEvent + { + TracerId = tracerId, + IsSpectatorShooter = isSpectatorShooter, + ShooterId = shooterEntityId, + StartX = start.X, StartY = start.Y, StartZ = start.Z, + EndX = end.X, EndY = end.Y, EndZ = end.Z, + ColorRgba = colorRgba, + Ttl = ttl, + WeaponClass = (byte)weaponClass, + WeaponId = weaponId + }); + } + + void IOrdnanceTargetSink.EmitNonActorHit( + HitTargetKind targetKind, + int targetId, + Vector3 hitPoint, + Vector3 normal, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + bool isSpectatorShooter, + int shooterEntityId) + { + long hitId = State.AllocateHitEventId(); + State.HitEvents.Add(new HitFeedbackEvent( + EventId: hitId, + HitX: hitPoint.X, + HitY: hitPoint.Y, + HitZ: hitPoint.Z, + NormalX: normal.X, + NormalY: normal.Y, + NormalZ: normal.Z, + SourceX: shooterPos.X, + SourceY: shooterPos.Y, + SourceZ: shooterPos.Z, + TargetKind: targetKind, + TargetId: targetId, + CellX: 0, + CellY: 0, + WeaponClass: weaponClass, + WeaponId: weaponId, + IsAirburst: isAirburst, + Ttl: 0.35f)); + _stepEvents.Add(new HitImpactEvent + { + EventId = hitId, + HitX = hitPoint.X, HitY = hitPoint.Y, HitZ = hitPoint.Z, + NormalX = normal.X, NormalY = normal.Y, NormalZ = normal.Z, + SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z, + TargetKind = (byte)targetKind, + TargetId = targetId, + WeaponClass = (byte)weaponClass, + WeaponId = weaponId, + IsAirburst = isAirburst, + Ttl = 0.35f, + ShooterId = shooterEntityId, + IsContenderShooter = !isSpectatorShooter + }); + } + + void IOrdnanceTargetSink.StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius) + { + if (craterRadius > 0f && craterDepth > 0f) + { + State.Terrain.StampCrater(x, z, radius: craterRadius, depth: craterDepth); + _stepEvents.Add(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = x, + Z = z, + Radius = craterRadius, + Depth = craterDepth + }); + } + if (scorchRadius > 0f) + { + State.Terrain.StampScorch(x, z, radius: scorchRadius); + _stepEvents.Add(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Scorch, + X = x, + Z = z, + Radius = scorchRadius + }); } } @@ -3163,19 +3315,6 @@ namespace RustToDust.Ymir return bestY; } - private static Vector3 ApplyAimSpread(Vector3 baseDir, float yawOffset, float pitchOffset) - { - var yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawOffset); - var rotated = Vector3.Transform(baseDir, yawQ); - var right = Vector3.Cross(rotated, Vector3.UnitY); - if (right.LengthSquared() > 1e-4f) - { - var pitchQ = Quaternion.CreateFromAxisAngle(Vector3.Normalize(right), pitchOffset); - rotated = Vector3.Transform(rotated, pitchQ); - } - return Vector3.Normalize(rotated); - } - public void Dispose() { if (_disposed) diff --git a/src/RustToDust.Ymir/OrdnanceRuntime.cs b/src/RustToDust.Ymir/OrdnanceRuntime.cs new file mode 100644 index 0000000..1f4c3d2 --- /dev/null +++ b/src/RustToDust.Ymir/OrdnanceRuntime.cs @@ -0,0 +1,1795 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public enum OrdnanceEventKind : byte + { + Spawned = 0, + StageTransition = 1, + Split = 2, + Detonated = 3, + Intercepted = 4, + Expired = 5 + } + + public readonly record struct OrdnanceNetEvent( + int OrdnanceId, + int ParentOrdnanceId, + OrdnanceEventKind Kind, + ulong ShooterStableId, + bool IsSpectatorShooter, + int ShooterEntityId, + ProceduralWeaponKey? WeaponKey, + byte NodeDefIndex, + Vector3 Pos, + Vector3 Vel, + int TargetEntityId, + bool TargetIsSpectator, + float SimTime, + byte VisualShape, + uint ColorRgba); + + public readonly record struct OrdnanceFireRequest( + MountedModule Module, + ulong ShooterStableId, + ContenderState? ShooterContender, + string ShooterLabel, + bool IsSpectatorShooter, + int ShooterEntityId, + Vector3 ShooterPos, + Vector3 MuzzlePos, + Vector3 AimDir, + float AimDist, + float SpreadRad, + ulong TargetEntityStableId, + OrdnanceNodeDef RootDef, + ProceduralWeaponKey? WeaponKey); + + public interface IOrdnanceTargetSink + { + Box3DSoaWorld World { get; } + MatchState State { get; } + bool HasLineOfSight(float x0, float y0, float z0, float x1, float y1, float z1); + bool TryResolveActor(ulong stableId, out bool isContender, out int index); + Vector3 GetActorAimPosition(bool isContender, int index); + void ApplyDirectHit( + ulong targetStableId, + (float X, float Y, float Z) hitPoint, + Vector3 shotDir, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + float damage, + float heatTransfer, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId); + void ApplySplashDamage( + Vector3 center, + float radius, + float splashDamage, + float heatTransfer, + WeaponVisualClass weaponClass, + string weaponId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + ulong ignoreStableId); + void EmitTracer( + Vector3 start, + Vector3 end, + uint colorRgba, + float ttl, + WeaponVisualClass weaponClass, + string weaponId, + bool isSpectatorShooter, + int shooterEntityId); + void EmitNonActorHit( + HitTargetKind targetKind, + int targetId, + Vector3 hitPoint, + Vector3 normal, + Vector3 shooterPos, + WeaponVisualClass weaponClass, + string weaponId, + bool isAirburst, + bool isSpectatorShooter, + int shooterEntityId); + void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius); + } + + public struct LiveOrdnanceInstance + { + public bool Active; + public int OrdnanceId; + public int ParentOrdnanceId; + public ulong ShooterStableId; + public int ShooterContenderId; + public bool IsSpectatorShooter; + public string ShooterLabel; + public string WeaponId; + public ProceduralWeaponKey? WeaponKey; + public OrdnanceNodeDef Def; + public byte Depth; + public Vector3 Pos; + public Vector3 PrevPos; + public Vector3 Vel; + public Vector3 SurfaceNormal; + public Vector3 AnchorPos; + public Vector3 ShooterOriginPos; + public ulong TargetStableId; + public float Age; + public float StageAge; + public float WhileAliveTimer; + public int WhileAliveCount; + public float OrbitAngle; + public float Hp; + public bool Armed; + public bool EjectSabotVfx; + public byte PenetrationsUsed; + public ulong LastPenetratedStableId; + public float DamageScale; + public int CreatedStep; + } + + public sealed class OrdnanceRuntime + { + public const int PoolCapacity = 256; + + private readonly IOrdnanceTargetSink _sink; + private readonly LiveOrdnanceInstance[] _pool = new LiveOrdnanceInstance[PoolCapacity]; + private readonly List _netEvents = new(64); + private int _nextOrdnanceId = 1; + private int _stepCounter; + + public OrdnanceRuntime(IOrdnanceTargetSink sink) + { + _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + } + + public int ActiveCount { get; private set; } + public int MaxObservedDepth { get; private set; } + public ReadOnlySpan PoolSpan => _pool; + + public void Reset() + { + Array.Clear(_pool, 0, _pool.Length); + _netEvents.Clear(); + ActiveCount = 0; + MaxObservedDepth = 0; + _nextOrdnanceId = 1; + _stepCounter = 0; + } + + public void DrainNetEvents(List dest) + { + if (_netEvents.Count == 0) + { + return; + } + dest.AddRange(_netEvents); + _netEvents.Clear(); + } + + public void FireWeapon(in OrdnanceFireRequest req) + { + var mod = req.Module; + int burst = Math.Max(1, mod.Spec.BurstCount); + float perfScale = Math.Clamp(mod.CurrentPerformance, 0.05f, 1.5f); + float spread = MathF.Max(0f, req.SpreadRad); + var rng = _sink.State.Rng; + + for (int b = 0; b < burst; b++) + { + float yawJitter = ((float)rng.NextDouble() * 2f - 1f) * spread; + float pitchJitter = ((float)rng.NextDouble() * 2f - 1f) * (spread * 0.35f); + Vector3 dir = ApplySpread(req.AimDir, yawJitter, pitchJitter); + + if (req.RootDef.Motion == OrdnanceMotion.HitscanBeam) + { + ResolveHitscanBeam( + req.RootDef, + req.MuzzlePos, + dir, + req.AimDist, + req.ShooterPos, + req.ShooterStableId, + req.ShooterContender, + req.ShooterLabel, + req.IsSpectatorShooter, + req.ShooterEntityId, + mod.Spec.Id, + perfScale, + burstIndex: b); + } + else + { + Vector3 launchDir = ApplyPitchBias(dir, req.RootDef.LaunchPitchBiasDeg); + Vector3 vel = launchDir * req.RootDef.InitialSpeed; + SpawnInstance( + parentId: 0, + depth: 0, + req.RootDef, + req.ShooterStableId, + req.ShooterContender?.Id ?? -1, + req.IsSpectatorShooter, + req.ShooterLabel, + mod.Spec.Id, + req.WeaponKey, + req.MuzzlePos, + vel, + Vector3.UnitY, + req.ShooterPos, + req.TargetEntityStableId, + perfScale, + OrdnanceEventKind.Spawned, + createdStep: _stepCounter - 1); + } + } + } + + public void Step(float dt) + { + _stepCounter++; + var state = _sink.State; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active || _pool[i].CreatedStep == _stepCounter) + { + continue; + } + + ref var inst = ref _pool[i]; + var def = inst.Def; + + inst.PrevPos = inst.Pos; + inst.Age += dt; + inst.StageAge += dt; + + if (!inst.Armed && inst.StageAge >= def.ArmDelay) + { + inst.Armed = true; + } + + if (def.WhileAlive is { } wa) + { + StepWhileAlive(ref inst, wa, dt); + if (!inst.Active) + { + continue; + } + } + + Vector3 prevVel = inst.Vel; + Vector3 nextPos = AdvanceKinematics(ref inst, dt, state.Terrain); + + if (def.Motion is OrdnanceMotion.Ballistic or OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile) + { + if (SweepDynamicProjectile(i, nextPos, state.Terrain)) + { + continue; + } + } + else + { + inst.Pos = nextPos; + } + + EvaluatePostStepTriggers(i, prevVel, state.Terrain); + } + } + + public bool TryFindBestHostileAirborneOrdnance( + Vector3 muzzle, + ulong shooterStableId, + Quaternion shooterQuat, + float minPitchDeg, + float maxPitchDeg, + float maxRange, + out int ordnanceId, + out Vector3 targetPos) + { + ordnanceId = 0; + targetPos = Vector3.Zero; + float bestDistSq = maxRange * maxRange; + bool found = false; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active) + { + continue; + } + ref readonly var inst = ref _pool[i]; + if (inst.ShooterStableId == shooterStableId || inst.Def.InterceptHp <= 0f) + { + continue; + } + if (inst.Def.Motion is not (OrdnanceMotion.LoiterOrbit or OrdnanceMotion.HomingMissile)) + { + continue; + } + + Vector3 delta = inst.Pos - muzzle; + float d2 = delta.LengthSquared(); + if (d2 > bestDistSq || d2 < 1e-3f) + { + continue; + } + + float pitchDeg = MatchRules.ComputeLocalPitchDeg(delta, shooterQuat); + if (pitchDeg < minPitchDeg || pitchDeg > maxPitchDeg) + { + continue; + } + + if (!_sink.HasLineOfSight(muzzle.X, muzzle.Y, muzzle.Z, inst.Pos.X, inst.Pos.Y, inst.Pos.Z)) + { + continue; + } + + bestDistSq = d2; + ordnanceId = inst.OrdnanceId; + targetPos = inst.Pos; + found = true; + } + + return found; + } + + private void StepWhileAlive(ref LiveOrdnanceInstance inst, OrdnanceWhileAliveDef wa, float dt) + { + inst.WhileAliveTimer += dt; + if (inst.WhileAliveTimer < wa.Interval || inst.WhileAliveCount >= wa.MaxPulses) + { + return; + } + + inst.WhileAliveTimer -= wa.Interval; + inst.WhileAliveCount++; + + if (wa.ChildNode is { Motion: OrdnanceMotion.HitscanBeam } childBeam) + { + if (TryAcquireDownwardTarget(in inst, wa, out ulong targetStableId, out Vector3 aimPos)) + { + Vector3 dir = Vector3.Normalize(aimPos - inst.Pos); + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + + ResolveHitscanBeam( + childBeam, + inst.Pos, + dir, + aimDist: MathF.Max(childBeam.Range, Vector3.Distance(inst.Pos, aimPos) + 5f), + inst.Pos, + inst.ShooterStableId, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId, + inst.WeaponId, + inst.DamageScale, + burstIndex: 0); + } + } + + if ((wa.RadialDamage > 0f || wa.RadialHeat > 0f) && wa.RadialRadius > 0.1f) + { + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + _sink.ApplySplashDamage( + inst.Pos, + wa.RadialRadius, + wa.RadialDamage * inst.DamageScale, + wa.RadialHeat * inst.DamageScale, + inst.Def.VisualClass, + inst.WeaponId, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + shooterEntityId, + ignoreStableId: inst.Def.ProximityIgnoreOwner ? inst.ShooterStableId : 0UL); + } + } + + private bool TryAcquireDownwardTarget(in LiveOrdnanceInstance inst, OrdnanceWhileAliveDef wa, out ulong stableId, out Vector3 aimPos) + { + stableId = 0; + aimPos = Vector3.Zero; + float maxRange = MathF.Max(10f, wa.TriggerScanRadius); + float maxRangeSq = maxRange * maxRange; + float minDownCos = MathF.Cos(Math.Clamp(wa.TargetConeDeg, 5f, 89f) * MathF.PI / 180f); + float bestScore = float.PositiveInfinity; + var state = _sink.State; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ArenaSession.ContenderStableIdBase + (ulong)c.Id; + if (cStable == inst.ShooterStableId) + { + continue; + } + + Vector3 targetPt = _sink.GetActorAimPosition(true, i); + Vector3 delta = targetPt - inst.Pos; + float d2 = delta.LengthSquared(); + if (d2 > maxRangeSq || d2 < 1e-3f) + { + continue; + } + + Vector3 dir = delta / MathF.Sqrt(d2); + if (Vector3.Dot(dir, -Vector3.UnitY) < minDownCos) + { + continue; + } + + if (!_sink.HasLineOfSight(inst.Pos.X, inst.Pos.Y, inst.Pos.Z, targetPt.X, targetPt.Y, targetPt.Z)) + { + continue; + } + + if (d2 < bestScore) + { + bestScore = d2; + stableId = cStable; + aimPos = targetPt; + } + } + + // Never lock onto Neutral Spectators! + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) + { + continue; + } + ulong sStable = 3000UL + (ulong)s.Id; + if (sStable == inst.ShooterStableId) + { + continue; + } + + Vector3 targetPt = _sink.GetActorAimPosition(false, i); + Vector3 delta = targetPt - inst.Pos; + float d2 = delta.LengthSquared(); + if (d2 > maxRangeSq || d2 < 1e-3f) + { + continue; + } + + Vector3 dir = delta / MathF.Sqrt(d2); + if (Vector3.Dot(dir, -Vector3.UnitY) < minDownCos) + { + continue; + } + + if (!_sink.HasLineOfSight(inst.Pos.X, inst.Pos.Y, inst.Pos.Z, targetPt.X, targetPt.Y, targetPt.Z)) + { + continue; + } + + if (d2 < bestScore) + { + bestScore = d2; + stableId = sStable; + aimPos = targetPt; + } + } + + return stableId != 0; + } + + private Vector3 AdvanceKinematics(ref LiveOrdnanceInstance inst, float dt, TerrainField terrain) + { + var def = inst.Def; + switch (def.Motion) + { + case OrdnanceMotion.Ballistic: + { + inst.Vel.Y -= 20f * def.GravityScale * dt; + return inst.Pos + inst.Vel * dt; + } + + case OrdnanceMotion.RocketBoosted: + { + float speed = inst.Vel.Length(); + Vector3 dir = speed > 1e-4f ? inst.Vel / speed : Vector3.UnitZ; + if (inst.StageAge <= def.BurnTime && def.ThrustAccel > 0f) + { + float maxSpd = def.MaxSpeed > 0f ? def.MaxSpeed : 400f; + speed = MathF.Min(maxSpd, speed + def.ThrustAccel * dt); + inst.Vel = dir * speed; + } + else if (def.GravityScale > 0f) + { + inst.Vel.Y -= 20f * def.GravityScale * 0.25f * dt; + } + return inst.Pos + inst.Vel * dt; + } + + case OrdnanceMotion.HomingMissile: + { + float speed = inst.Vel.Length(); + Vector3 dir = speed > 1e-4f ? inst.Vel / speed : Vector3.UnitZ; + + if (TryResolveHomingTarget(ref inst, dir, out Vector3 targetPos)) + { + Vector3 toTarget = targetPos - inst.Pos; + if (toTarget.LengthSquared() > 1e-4f) + { + Vector3 desiredDir = Vector3.Normalize(toTarget); + float maxTurn = MathF.Max(0.5f, def.TurnRateRad) * dt; + dir = RotateTowards(dir, desiredDir, maxTurn); + } + } + + if (inst.StageAge <= def.BurnTime || def.BurnTime <= 0f) + { + float maxSpd = def.MaxSpeed > 0f ? def.MaxSpeed : 180f; + speed = MathF.Min(maxSpd, speed + def.ThrustAccel * dt); + } + inst.Vel = dir * speed; + return inst.Pos + inst.Vel * dt; + } + + case OrdnanceMotion.LoiterOrbit: + { + // Gently drift anchor toward nearest hostile within 120m so loitering drones track moving targets + if (TryFindNearestHostile(in inst, 120f, ignoreNeutralSpectators: true, out ulong targetId, out Vector3 targetPos)) + { + inst.TargetStableId = targetId; + Vector3 toTarget = new Vector3(targetPos.X - inst.AnchorPos.X, 0f, targetPos.Z - inst.AnchorPos.Z); + float horizDist = toTarget.Length(); + if (horizDist > 4f) + { + inst.AnchorPos += (toTarget / horizDist) * MathF.Min(horizDist, 10f * dt); + } + } + + inst.OrbitAngle += def.LoiterOrbitSpeedRad * dt; + float targetX = inst.AnchorPos.X + MathF.Cos(inst.OrbitAngle) * def.LoiterOrbitRadius; + float targetZ = inst.AnchorPos.Z + MathF.Sin(inst.OrbitAngle) * def.LoiterOrbitRadius; + float groundY = terrain.SampleHeight(targetX, targetZ); + float desiredY = groundY + def.LoiterAltitudeAgl; + float nextY = inst.Pos.Y + (desiredY - inst.Pos.Y) * Math.Clamp(dt * 4.0f, 0f, 1f); + var nextPos = new Vector3(targetX, nextY, targetZ); + inst.Vel = (nextPos - inst.Pos) / MathF.Max(1e-4f, dt); + return nextPos; + } + + case OrdnanceMotion.StationaryMine: + default: + inst.Vel = Vector3.Zero; + return inst.Pos; + } + } + + private bool TryResolveHomingTarget(ref LiveOrdnanceInstance inst, Vector3 currentDir, out Vector3 targetPos) + { + targetPos = Vector3.Zero; + if (inst.TargetStableId != 0 && _sink.TryResolveActor(inst.TargetStableId, out bool isContender, out int idx)) + { + if (isContender) + { + var c = _sink.State.Contenders[idx]; + if (c.IsGroundedActive) + { + targetPos = _sink.GetActorAimPosition(true, idx); + return true; + } + } + else + { + var s = _sink.State.Spectators.Spectators[idx]; + if (s.Alive && s.Stance != SpectatorStance.Neutral) + { + targetPos = _sink.GetActorAimPosition(false, idx); + return true; + } + } + } + + float range = inst.Def.SeekerRange > 0f ? inst.Def.SeekerRange : 180f; + float minCos = MathF.Cos(Math.Clamp(inst.Def.SeekerConeDeg * 0.5f, 10f, 179f) * MathF.PI / 180f); + float bestDistSq = range * range; + ulong bestId = 0; + var state = _sink.State; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ArenaSession.ContenderStableIdBase + (ulong)c.Id; + if (cStable == inst.ShooterStableId) + { + continue; + } + Vector3 pt = _sink.GetActorAimPosition(true, i); + Vector3 d = pt - inst.Pos; + float d2 = d.LengthSquared(); + if (d2 > bestDistSq || d2 < 1e-4f) + { + continue; + } + if (Vector3.Dot(d / MathF.Sqrt(d2), currentDir) >= minCos) + { + bestDistSq = d2; + bestId = cStable; + targetPos = pt; + } + } + + if (bestId != 0) + { + inst.TargetStableId = bestId; + return true; + } + + return false; + } + + private bool TryFindNearestHostile( + in LiveOrdnanceInstance inst, + float maxRadius, + bool ignoreNeutralSpectators, + out ulong stableId, + out Vector3 targetPos) + { + stableId = 0; + targetPos = Vector3.Zero; + float bestDistSq = maxRadius * maxRadius; + var state = _sink.State; + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + ulong cStable = ArenaSession.ContenderStableIdBase + (ulong)c.Id; + if (inst.Def.ProximityIgnoreOwner && cStable == inst.ShooterStableId) + { + continue; + } + if (cStable == inst.ShooterStableId && inst.Age < 0.3f) + { + continue; + } + + Vector3 pt = _sink.GetActorAimPosition(true, i); + float d2 = Vector3.DistanceSquared(inst.Pos, pt); + // Allow horizontal proximity trigger for mines even on tall walkers + float dx = pt.X - inst.Pos.X; + float dz = pt.Z - inst.Pos.Z; + float dy = MathF.Abs(pt.Y - inst.Pos.Y); + float effectiveDistSq = dx * dx + dz * dz; + if (dy <= maxRadius + c.Grid.Spec.HalfHeight && effectiveDistSq <= bestDistSq && d2 <= (maxRadius + c.Grid.Spec.HalfHeight + 1.5f) * (maxRadius + c.Grid.Spec.HalfHeight + 1.5f)) + { + bestDistSq = effectiveDistSq; + stableId = cStable; + targetPos = pt; + } + } + + if (!ignoreNeutralSpectators) + { + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) + { + continue; + } + ulong sStable = 3000UL + (ulong)s.Id; + if (sStable == inst.ShooterStableId) + { + continue; + } + Vector3 pt = _sink.GetActorAimPosition(false, i); + float d2 = Vector3.DistanceSquared(inst.Pos, pt); + if (d2 <= bestDistSq) + { + bestDistSq = d2; + stableId = sStable; + targetPos = pt; + } + } + } + + return stableId != 0; + } + + private bool SweepDynamicProjectile(int slotIndex, Vector3 nextPos, TerrainField terrain) + { + ref var inst = ref _pool[slotIndex]; + Vector3 segStart = inst.Pos; + Vector3 segDelta = nextPos - segStart; + float segLen = segDelta.Length(); + if (segLen < 1e-5f) + { + inst.Pos = nextPos; + return false; + } + + Vector3 dir = segDelta / segLen; + Vector3 castOrigin = segStart; + float remaining = segLen; + bool skipSelf = inst.Age < 0.25f; + + for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++) + { + var rayHit = _sink.World.CastRayClosest( + (castOrigin.X, castOrigin.Y, castOrigin.Z), + (dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); + + float boxDist = remaining + 1f; + bool hitBox = false; + ulong hitStableId = 0; + Vector3 boxPoint = Vector3.Zero; + Vector3 boxNormal = -dir; + + if (rayHit.Hit) + { + boxPoint = new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z); + float hitDistFromStart = Vector3.Distance(segStart, boxPoint); + if ((skipSelf && rayHit.StableId == inst.ShooterStableId) || + (inst.LastPenetratedStableId != 0 && rayHit.StableId == inst.LastPenetratedStableId)) + { + float advance = Vector3.Distance(castOrigin, boxPoint) + 0.12f; + castOrigin += dir * advance; + remaining -= advance; + continue; + } + + hitBox = true; + hitStableId = rayHit.StableId; + boxDist = hitDistFromStart; + Vector3 rn = new(rayHit.Normal.X, rayHit.Normal.Y, rayHit.Normal.Z); + if (rn.LengthSquared() > 1e-4f) + { + boxNormal = Vector3.Normalize(rn); + } + } + + bool hitTerrain = terrain.Raycast( + segStart.X, segStart.Y, segStart.Z, + dir.X, dir.Y, dir.Z, + MathF.Min(segLen, boxDist), + out float tx, out float ty, out float tz, out float terrainDist); + + if (hitTerrain && (!hitBox || terrainDist <= boxDist)) + { + var hitPt = new Vector3(tx, ty, tz); + var (tnx, tny, tnz) = terrain.SampleNormal(tx, tz); + var normal = new Vector3(tnx, tny, tnz); + inst.Pos = hitPt; + HandleProjectileImpact(slotIndex, HitTargetKind.Terrain, -1, 0UL, hitPt, normal, dir); + return !inst.Active; + } + + if (hitBox) + { + if (_sink.TryResolveActor(hitStableId, out bool isContender, out int actorIdx)) + { + if (inst.PenetrationsUsed < inst.Def.MaxPenetrations) + { + ApplyActorDirectHit(in inst, hitStableId, boxPoint, dir); + inst.PenetrationsUsed++; + inst.DamageScale *= inst.Def.PenetrationDamageDecay; + inst.LastPenetratedStableId = hitStableId; + float advance = Vector3.Distance(castOrigin, boxPoint) + 0.15f; + castOrigin += dir * advance; + remaining -= advance; + continue; + } + + inst.Pos = boxPoint; + int targetId = isContender + ? _sink.State.Contenders[actorIdx].Id + : _sink.State.Spectators.Spectators[actorIdx].Id; + HandleProjectileImpact( + slotIndex, + isContender ? HitTargetKind.Contender : HitTargetKind.Spectator, + targetId, + hitStableId, + boxPoint, + boxNormal, + dir); + return !inst.Active; + } + + inst.Pos = boxPoint; + HandleProjectileImpact( + slotIndex, + HitTargetKind.StaticCover, + (int)hitStableId, + hitStableId, + boxPoint, + boxNormal, + dir); + return !inst.Active; + } + + break; + } + + inst.Pos = nextPos; + return false; + } + + private void HandleProjectileImpact( + int slotIndex, + HitTargetKind targetKind, + int targetId, + ulong targetStableId, + Vector3 hitPoint, + Vector3 surfaceNormal, + Vector3 shotDir) + { + ref var inst = ref _pool[slotIndex]; + var def = inst.Def; + + for (int t = 0; t < def.Triggers.Length; t++) + { + var tr = def.Triggers[t]; + if (tr.Kind != OrdnanceTriggerKind.Impact) + { + continue; + } + if (inst.StageAge < tr.MinAge) + { + continue; + } + + ExecuteTriggerRule(slotIndex, tr, targetKind, targetId, targetStableId, hitPoint, surfaceNormal, shotDir); + return; + } + + // Default fallback on impact if no explicit Impact rule exists + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, hitPoint, surfaceNormal, shotDir, burstIndex: 0); + } + + private void EvaluatePostStepTriggers(int slotIndex, Vector3 prevVel, TerrainField terrain) + { + ref var inst = ref _pool[slotIndex]; + if (!inst.Active) + { + return; + } + + var def = inst.Def; + for (int t = 0; t < def.Triggers.Length; t++) + { + var tr = def.Triggers[t]; + if (inst.StageAge < tr.MinAge) + { + continue; + } + + switch (tr.Kind) + { + case OrdnanceTriggerKind.StageElapsed: + if (inst.StageAge >= tr.Threshold) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : Vector3.UnitZ; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + + case OrdnanceTriggerKind.Timeout: + if (inst.StageAge >= tr.Threshold) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : -Vector3.UnitY; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + + case OrdnanceTriggerKind.Apex: + if (inst.Vel.Y <= 0f && (prevVel.Y > 0f || inst.StageAge >= MathF.Max(0.15f, tr.MinAge))) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : Vector3.UnitZ; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + + case OrdnanceTriggerKind.Altitude: + { + float agl = inst.Pos.Y - terrain.SampleHeight(inst.Pos.X, inst.Pos.Z); + if (agl <= tr.Threshold) + { + Vector3 dir = inst.Vel.LengthSquared() > 1e-4f ? Vector3.Normalize(inst.Vel) : -Vector3.UnitY; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, 0UL, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + } + + case OrdnanceTriggerKind.Proximity: + if (inst.Armed && TryFindNearestHostile(in inst, tr.Threshold, ignoreNeutralSpectators: true, out ulong proxTarget, out Vector3 proxPos)) + { + Vector3 dir = (proxPos - inst.Pos).LengthSquared() > 1e-4f + ? Vector3.Normalize(proxPos - inst.Pos) + : Vector3.UnitY; + ExecuteTriggerRule(slotIndex, tr, HitTargetKind.Terrain, -1, proxTarget, inst.Pos, Vector3.UnitY, dir); + return; + } + break; + } + } + + if (def.MaxLifetime > 0f && inst.StageAge >= def.MaxLifetime) + { + EmitNetEvent(in inst, OrdnanceEventKind.Expired); + FreeSlot(slotIndex); + } + } + + private void ExecuteTriggerRule( + int slotIndex, + OrdnanceTriggerRule rule, + HitTargetKind targetKind, + int targetId, + ulong targetStableId, + Vector3 pos, + Vector3 normal, + Vector3 shotDir) + { + ref var inst = ref _pool[slotIndex]; + switch (rule.Action) + { + case OrdnanceTriggerAction.Detonate: + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, pos, normal, shotDir, burstIndex: 0); + break; + + case OrdnanceTriggerAction.Fizzle: + EmitNetEvent(in inst, OrdnanceEventKind.Expired); + FreeSlot(slotIndex); + break; + + case OrdnanceTriggerAction.Transition: + { + if (rule.ChildNode is null || inst.Depth + 1 >= OrdnanceNodeDef.MaxAllowedDepth) + { + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, pos, normal, shotDir, burstIndex: 0); + return; + } + + var childDef = rule.ChildNode; + Vector3 childPos = pos; + Vector3 childVel = shotDir * childDef.InitialSpeed; + + if (childDef.Motion == OrdnanceMotion.StationaryMine) + { + float gh = _sink.State.Terrain.SampleHeight(pos.X, pos.Z); + if (targetKind is HitTargetKind.Contender or HitTargetKind.Spectator || pos.Y > gh + 3.0f) + { + childPos = new Vector3(pos.X, gh + 0.25f, pos.Z); + } + else + { + childPos = pos + normal * 0.25f; + } + childVel = Vector3.Zero; + } + else if (childDef.Motion == OrdnanceMotion.HomingMissile && inst.TargetStableId != 0) + { + if (_sink.TryResolveActor(inst.TargetStableId, out bool ic, out int idx)) + { + Vector3 tPos = _sink.GetActorAimPosition(ic, idx); + if ((tPos - pos).LengthSquared() > 1e-3f) + { + childVel = Vector3.Normalize(tPos - pos) * childDef.InitialSpeed; + } + } + } + + // Capture parent metadata before freeing + int parentId = inst.OrdnanceId; + byte childDepth = (byte)(inst.Depth + 1); + ulong shooterStableId = inst.ShooterStableId; + int shooterContenderId = inst.ShooterContenderId; + bool isSpec = inst.IsSpectatorShooter; + string shooterLabel = inst.ShooterLabel; + string weaponId = inst.WeaponId; + ProceduralWeaponKey? key = inst.WeaponKey; + Vector3 originPos = inst.ShooterOriginPos; + ulong tgt = inst.TargetStableId; + float scale = inst.DamageScale; + + FreeSlot(slotIndex); + SpawnInstance( + parentId, + childDepth, + childDef, + shooterStableId, + shooterContenderId, + isSpec, + shooterLabel, + weaponId, + key, + childPos, + childVel, + normal, + originPos, + tgt, + scale, + OrdnanceEventKind.StageTransition, + createdStep: _stepCounter); + break; + } + + case OrdnanceTriggerAction.Split: + { + if (rule.ChildNode is null || inst.Depth + 1 >= OrdnanceNodeDef.MaxAllowedDepth) + { + ExecuteDetonate(slotIndex, targetKind, targetId, targetStableId, pos, normal, shotDir, burstIndex: 0); + return; + } + + var childDef = rule.ChildNode; + int count = Math.Clamp(rule.SplitCount, 1, OrdnanceNodeDef.MaxShotSubSpawnBudget); + float coneRad = Math.Clamp(rule.SplitConeDeg, 5f, 170f) * MathF.PI / 180f; + + int parentId = inst.OrdnanceId; + byte childDepth = (byte)(inst.Depth + 1); + ulong shooterStableId = inst.ShooterStableId; + int shooterContenderId = inst.ShooterContenderId; + bool isSpec = inst.IsSpectatorShooter; + string shooterLabel = inst.ShooterLabel; + string weaponId = inst.WeaponId; + ProceduralWeaponKey? key = inst.WeaponKey; + Vector3 originPos = inst.ShooterOriginPos; + ulong tgt = inst.TargetStableId; + float scale = inst.DamageScale; + + EmitNetEvent(in inst, OrdnanceEventKind.Split); + FreeSlot(slotIndex); + + Vector3 forwardBase = new Vector3(shotDir.X, 0f, shotDir.Z); + forwardBase = forwardBase.LengthSquared() > 1e-4f + ? Vector3.Normalize(forwardBase * 0.85f - Vector3.UnitY * 0.55f) + : -Vector3.UnitY; + + if (targetKind is HitTargetKind.Terrain or HitTargetKind.StaticCover or HitTargetKind.Contender) + { + if (childDef.Motion == OrdnanceMotion.Ballistic && Vector3.Dot(shotDir, normal) < 0f) + { + forwardBase = Vector3.Normalize(Vector3.Reflect(shotDir, normal) + normal * 0.35f); + } + } + + var rng = _sink.State.Rng; + for (int k = 0; k < count; k++) + { + float frac = count == 1 ? 0f : (k / (float)count) * MathF.Tau; + float radial = coneRad * (0.35f + 0.65f * ((k % 3 + 1) / 3f)); + float yawOff = MathF.Cos(frac) * radial + ((float)rng.NextDouble() - 0.5f) * 0.08f; + float pitchOff = MathF.Sin(frac) * radial * 0.5f; + Vector3 cDir = ApplySpread(forwardBase, yawOff, pitchOff); + Vector3 cPos = pos + normal * 0.25f; + Vector3 cVel = cDir * childDef.InitialSpeed; + + SpawnInstance( + parentId, + childDepth, + childDef, + shooterStableId, + shooterContenderId, + isSpec, + shooterLabel, + weaponId, + key, + cPos, + cVel, + normal, + originPos, + tgt, + scale, + OrdnanceEventKind.Spawned, + createdStep: _stepCounter); + } + break; + } + } + } + + private void ExecuteDetonate( + int slotIndex, + HitTargetKind targetKind, + int targetId, + ulong targetStableId, + Vector3 hitPoint, + Vector3 surfaceNormal, + Vector3 shotDir, + int burstIndex) + { + ref var inst = ref _pool[slotIndex]; + var def = inst.Def; + + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + ulong directActorId = 0; + if (targetKind is HitTargetKind.Contender or HitTargetKind.Spectator && targetStableId != 0) + { + directActorId = targetStableId; + ApplyActorDirectHit(in inst, targetStableId, hitPoint, shotDir); + } + else if (targetKind == HitTargetKind.Terrain) + { + bool allowCrater = !def.CraterFirstBurstOnly || burstIndex == 0; + if (allowCrater && (def.CraterRadius > 0f || def.ScorchRadius > 0f)) + { + _sink.StampTerrainImpact(hitPoint.X, hitPoint.Z, def.CraterRadius, def.CraterDepth, def.ScorchRadius); + } + _sink.EmitNonActorHit( + HitTargetKind.Terrain, + -1, + hitPoint, + surfaceNormal, + inst.ShooterOriginPos, + def.VisualClass, + inst.WeaponId, + def.IsAirburst, + inst.IsSpectatorShooter, + shooterEntityId); + } + else + { + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + targetId, + hitPoint, + surfaceNormal, + inst.ShooterOriginPos, + def.VisualClass, + inst.WeaponId, + def.IsAirburst, + inst.IsSpectatorShooter, + shooterEntityId); + } + + if (def.SplashDamage > 0f && def.SplashRadius > 0.1f) + { + if (targetKind != HitTargetKind.Terrain && (def.CraterRadius > 0f || def.ScorchRadius > 0f)) + { + float groundY = _sink.State.Terrain.SampleHeight(hitPoint.X, hitPoint.Z); + if (hitPoint.Y - groundY <= def.SplashRadius) + { + _sink.StampTerrainImpact(hitPoint.X, hitPoint.Z, def.CraterRadius * 0.8f, def.CraterDepth * 0.7f, def.ScorchRadius); + } + } + + _sink.ApplySplashDamage( + hitPoint, + def.SplashRadius, + def.SplashDamage * inst.DamageScale, + def.HeatTransfer * inst.DamageScale, + def.VisualClass, + inst.WeaponId, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + shooterEntityId, + ignoreStableId: directActorId); + } + + EmitNetEvent(in inst, OrdnanceEventKind.Detonated); + FreeSlot(slotIndex); + } + + private void ApplyActorDirectHit(in LiveOrdnanceInstance inst, ulong targetStableId, Vector3 hitPoint, Vector3 shotDir) + { + ContenderState? shooterContender = !inst.IsSpectatorShooter && + inst.ShooterContenderId >= 0 && + inst.ShooterContenderId < _sink.State.Contenders.Count + ? _sink.State.Contenders[inst.ShooterContenderId] + : null; + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + _sink.ApplyDirectHit( + targetStableId, + (hitPoint.X, hitPoint.Y, hitPoint.Z), + shotDir, + inst.ShooterOriginPos, + inst.Def.VisualClass, + inst.WeaponId, + inst.Def.IsAirburst, + inst.Def.DirectDamage * inst.DamageScale, + inst.Def.HeatTransfer * inst.DamageScale, + shooterContender, + inst.ShooterLabel, + inst.IsSpectatorShooter, + shooterEntityId); + } + + private void ResolveHitscanBeam( + OrdnanceNodeDef def, + Vector3 muzzle, + Vector3 dir, + float aimDist, + Vector3 shooterPos, + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + int shooterEntityId, + string weaponId, + float damageScale, + int burstIndex) + { + float range = MathF.Max(5f, def.Range); + Vector3 castOrigin = muzzle; + float remainingRange = range; + int penetrations = 0; + ulong lastPenetratedId = 0; + float currDmgScale = damageScale; + + bool hitAny = false; + ulong hitStableId = 0; + (float X, float Y, float Z) hitPoint = default; + Vector3 hitNormal = -dir; + + for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++) + { + var rayHit = _sink.World.CastRayClosest( + (castOrigin.X, castOrigin.Y, castOrigin.Z), + (dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange)); + + // Also check interceptable airborne ordnance along [castOrigin .. castOrigin + dir * maxDist] + float rayDist = rayHit.Hit + ? Vector3.Distance(castOrigin, new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z)) + : remainingRange; + if (TryHitInterceptableOrdnance(castOrigin, dir, rayDist, shooterStableId, out int ordSlot, out float ordDist, out Vector3 ordHitPt)) + { + if (ordDist < rayDist) + { + ref var targetOrd = ref _pool[ordSlot]; + targetOrd.Hp -= def.DirectDamage * currDmgScale; + if (targetOrd.Hp <= 0f) + { + EmitNetEvent(in targetOrd, OrdnanceEventKind.Intercepted); + FreeSlot(ordSlot); + } + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + -1, + ordHitPt, + -dir, + shooterPos, + def.VisualClass, + weaponId, + isAirburst: true, + isSpectatorShooter, + shooterEntityId); + _sink.EmitTracer(muzzle, ordHitPt, def.ColorRgba, def.TracerTtl, def.VisualClass, weaponId, isSpectatorShooter, shooterEntityId); + return; + } + } + + if (!rayHit.Hit) + { + break; + } + + var ptVec = new Vector3(rayHit.Point.X, rayHit.Point.Y, rayHit.Point.Z); + if (rayHit.StableId == shooterStableId || (lastPenetratedId != 0 && rayHit.StableId == lastPenetratedId)) + { + float skip = MathF.Max(0.15f, Vector3.Distance(castOrigin, ptVec) + 0.08f); + castOrigin += dir * skip; + remainingRange = MathF.Max(0f, remainingRange - skip); + continue; + } + + if (_sink.TryResolveActor(rayHit.StableId, out _, out _) && penetrations < def.MaxPenetrations) + { + _sink.ApplyDirectHit( + rayHit.StableId, + rayHit.Point, + dir, + shooterPos, + def.VisualClass, + weaponId, + def.IsAirburst, + def.DirectDamage * currDmgScale, + def.HeatTransfer * currDmgScale, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId); + penetrations++; + currDmgScale *= def.PenetrationDamageDecay; + lastPenetratedId = rayHit.StableId; + float skip = MathF.Max(0.25f, Vector3.Distance(castOrigin, ptVec) + 0.12f); + castOrigin += dir * skip; + remainingRange = MathF.Max(0f, remainingRange - skip); + continue; + } + + hitAny = true; + hitStableId = rayHit.StableId; + hitPoint = rayHit.Point; + Vector3 rn = new(rayHit.Normal.X, rayHit.Normal.Y, rayHit.Normal.Z); + if (rn.LengthSquared() > 1e-4f) + { + hitNormal = Vector3.Normalize(rn); + } + break; + } + + float boxDist = hitAny + ? Vector3.Distance(muzzle, new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z)) + : range; + + bool hitTerrain = _sink.State.Terrain.Raycast( + muzzle.X, muzzle.Y, muzzle.Z, + dir.X, dir.Y, dir.Z, + boxDist, + out float tx, out float ty, out float tz, out float terrainDist); + + Vector3 endPt; + if (hitTerrain && terrainDist < boxDist) + { + endPt = new Vector3(tx, ty, tz); + bool allowCrater = !def.CraterFirstBurstOnly || burstIndex == 0; + if (allowCrater && (def.CraterRadius > 0f || def.ScorchRadius > 0f)) + { + _sink.StampTerrainImpact(tx, tz, def.CraterRadius, def.CraterDepth, def.ScorchRadius); + } + + var (tnx, tny, tnz) = _sink.State.Terrain.SampleNormal(tx, tz); + _sink.EmitNonActorHit( + HitTargetKind.Terrain, + -1, + endPt, + new Vector3(tnx, tny, tnz), + shooterPos, + def.VisualClass, + weaponId, + isAirburst: false, + isSpectatorShooter, + shooterEntityId); + + if (def.SplashDamage > 0f && def.SplashRadius > 0.1f) + { + _sink.ApplySplashDamage(endPt, def.SplashRadius, def.SplashDamage * currDmgScale, def.HeatTransfer * currDmgScale, def.VisualClass, weaponId, shooterContender, shooterLabel, isSpectatorShooter, shooterEntityId, ignoreStableId: 0UL); + } + + SpawnHitscanImpactChildren(def, endPt, new Vector3(tnx, tny, tnz), dir, shooterStableId, shooterContender, shooterLabel, isSpectatorShooter, shooterPos, weaponId, currDmgScale); + } + else + { + endPt = hitAny + ? new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) + : muzzle + dir * range; + + if (hitAny && hitStableId != shooterStableId && _sink.TryResolveActor(hitStableId, out _, out _)) + { + _sink.ApplyDirectHit( + hitStableId, + hitPoint, + dir, + shooterPos, + def.VisualClass, + weaponId, + def.IsAirburst, + def.DirectDamage * currDmgScale, + def.HeatTransfer * currDmgScale, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterEntityId); + + if (def.SplashDamage > 0f && def.SplashRadius > 0.1f) + { + _sink.ApplySplashDamage(endPt, def.SplashRadius, def.SplashDamage * currDmgScale, def.HeatTransfer * currDmgScale, def.VisualClass, weaponId, shooterContender, shooterLabel, isSpectatorShooter, shooterEntityId, ignoreStableId: hitStableId); + } + + SpawnHitscanImpactChildren(def, endPt, hitNormal, dir, shooterStableId, shooterContender, shooterLabel, isSpectatorShooter, shooterPos, weaponId, currDmgScale); + } + else if (hitAny && hitStableId != shooterStableId) + { + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + (int)hitStableId, + endPt, + -dir, + shooterPos, + def.VisualClass, + weaponId, + def.IsAirburst, + isSpectatorShooter, + shooterEntityId); + + SpawnHitscanImpactChildren(def, endPt, hitNormal, dir, shooterStableId, shooterContender, shooterLabel, isSpectatorShooter, shooterPos, weaponId, currDmgScale); + } + else if (def.IsAirburst && burstIndex == 0) + { + Vector3 airPt = muzzle + dir * MathF.Min(range, MathF.Max(20f, aimDist)); + _sink.EmitNonActorHit( + HitTargetKind.StaticCover, + -1, + airPt, + -dir, + shooterPos, + def.VisualClass, + weaponId, + isAirburst: true, + isSpectatorShooter, + shooterEntityId); + } + } + + _sink.EmitTracer(muzzle, endPt, def.ColorRgba, def.TracerTtl, def.VisualClass, weaponId, isSpectatorShooter, shooterEntityId); + } + + private void SpawnHitscanImpactChildren( + OrdnanceNodeDef def, + Vector3 hitPt, + Vector3 normal, + Vector3 shotDir, + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + Vector3 shooterPos, + string weaponId, + float scale) + { + if (def.Depth + 1 >= OrdnanceNodeDef.MaxAllowedDepth) + { + return; + } + + for (int t = 0; t < def.Triggers.Length; t++) + { + var tr = def.Triggers[t]; + if (tr.Kind == OrdnanceTriggerKind.Impact && + tr.Action == OrdnanceTriggerAction.Split && + tr.ChildNode is not null) + { + int count = Math.Clamp(tr.SplitCount, 1, OrdnanceNodeDef.MaxShotSubSpawnBudget); + float coneRad = Math.Clamp(tr.SplitConeDeg, 5f, 170f) * MathF.PI / 180f; + Vector3 bounceBase = Vector3.Normalize(Vector3.Reflect(shotDir, normal) + normal * 0.45f); + var rng = _sink.State.Rng; + + for (int k = 0; k < count; k++) + { + float ang = (k / (float)count) * MathF.Tau; + float yawOff = MathF.Cos(ang) * coneRad * 0.65f + ((float)rng.NextDouble() - 0.5f) * 0.1f; + float pitchOff = MathF.Sin(ang) * coneRad * 0.35f; + Vector3 cDir = ApplySpread(bounceBase, yawOff, pitchOff); + SpawnInstance( + parentId: 0, + depth: (byte)(def.Depth + 1), + tr.ChildNode, + shooterStableId, + shooterContender?.Id ?? -1, + isSpectatorShooter, + shooterLabel, + weaponId, + weaponKey: null, + hitPt + normal * 0.25f, + cDir * tr.ChildNode.InitialSpeed, + normal, + shooterPos, + targetStableId: 0UL, + scale, + OrdnanceEventKind.Spawned, + createdStep: _stepCounter); + } + return; + } + } + } + + private bool TryHitInterceptableOrdnance( + Vector3 origin, + Vector3 dir, + float maxDist, + ulong shooterStableId, + out int bestSlot, + out float bestDist, + out Vector3 hitPt) + { + bestSlot = -1; + bestDist = maxDist; + hitPt = Vector3.Zero; + + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active) + { + continue; + } + ref readonly var inst = ref _pool[i]; + if (inst.ShooterStableId == shooterStableId || inst.Def.InterceptHp <= 0f) + { + continue; + } + + float radius = inst.Def.Motion == OrdnanceMotion.LoiterOrbit ? 1.8f : 1.0f; + Vector3 m = origin - inst.Pos; + float b = Vector3.Dot(m, dir); + float c = Vector3.Dot(m, m) - radius * radius; + if (c > 0f && b > 0f) + { + continue; + } + float discr = b * b - c; + if (discr < 0f) + { + continue; + } + float t = MathF.Max(0f, -b - MathF.Sqrt(discr)); + if (t <= bestDist) + { + bestDist = t; + bestSlot = i; + hitPt = origin + dir * t; + } + } + + return bestSlot >= 0; + } + + private int SpawnInstance( + int parentId, + byte depth, + OrdnanceNodeDef def, + ulong shooterStableId, + int shooterContenderId, + bool isSpectatorShooter, + string shooterLabel, + string weaponId, + ProceduralWeaponKey? weaponKey, + Vector3 pos, + Vector3 vel, + Vector3 normal, + Vector3 shooterOriginPos, + ulong targetStableId, + float damageScale, + OrdnanceEventKind emitKind, + int createdStep) + { + if (depth >= OrdnanceNodeDef.MaxAllowedDepth) + { + return -1; + } + + int slot = FindFreeSlot(); + if (slot < 0) + { + slot = EvictLowestPrioritySlot(); + } + + int id = _nextOrdnanceId++; + if (depth > MaxObservedDepth) + { + MaxObservedDepth = depth; + } + + _pool[slot] = new LiveOrdnanceInstance + { + Active = true, + OrdnanceId = id, + ParentOrdnanceId = parentId, + ShooterStableId = shooterStableId, + ShooterContenderId = shooterContenderId, + IsSpectatorShooter = isSpectatorShooter, + ShooterLabel = shooterLabel, + WeaponId = weaponId, + WeaponKey = weaponKey, + Def = def, + Depth = depth, + Pos = pos, + PrevPos = pos, + Vel = vel, + SurfaceNormal = normal, + AnchorPos = pos, + ShooterOriginPos = shooterOriginPos, + TargetStableId = targetStableId, + Age = 0f, + StageAge = 0f, + WhileAliveTimer = def.WhileAlive is { } wa ? MathF.Max(0f, wa.Interval - 0.1f) : 0f, + WhileAliveCount = 0, + OrbitAngle = 0f, + Hp = def.InterceptHp, + Armed = def.ArmDelay <= 0f, + EjectSabotVfx = false, + PenetrationsUsed = 0, + LastPenetratedStableId = 0, + DamageScale = damageScale, + CreatedStep = createdStep + }; + + ActiveCount++; + EmitNetEvent(in _pool[slot], emitKind); + return slot; + } + + private int FindFreeSlot() + { + for (int i = 0; i < PoolCapacity; i++) + { + if (!_pool[i].Active) + { + return i; + } + } + return -1; + } + + private int EvictLowestPrioritySlot() + { + int bestIdx = 0; + int lowestTier = int.MaxValue; + float oldestAge = -1f; + + for (int i = 0; i < PoolCapacity; i++) + { + ref readonly var inst = ref _pool[i]; + if (!inst.Active) + { + return i; + } + + int tier = inst.Def.Motion switch + { + OrdnanceMotion.StationaryMine => 0, + OrdnanceMotion.Ballistic when inst.Depth > 0 => 1, + OrdnanceMotion.Ballistic or OrdnanceMotion.RocketBoosted => 2, + OrdnanceMotion.HomingMissile => 3, + OrdnanceMotion.LoiterOrbit => 4, + _ => 0 + }; + + if (tier < lowestTier || (tier == lowestTier && inst.Age > oldestAge)) + { + lowestTier = tier; + oldestAge = inst.Age; + bestIdx = i; + } + } + + EmitNetEvent(in _pool[bestIdx], OrdnanceEventKind.Expired); + FreeSlot(bestIdx); + return bestIdx; + } + + private void FreeSlot(int slotIndex) + { + if (_pool[slotIndex].Active) + { + _pool[slotIndex] = default; + ActiveCount--; + } + } + + private void EmitNetEvent(in LiveOrdnanceInstance inst, OrdnanceEventKind kind) + { + int shooterEntityId = inst.IsSpectatorShooter + ? (int)(inst.ShooterStableId - 3000UL) + : inst.ShooterContenderId; + + int targetEntityId = -1; + bool targetIsSpec = false; + if (inst.TargetStableId >= 3000UL) + { + targetIsSpec = true; + targetEntityId = (int)(inst.TargetStableId - 3000UL); + } + else if (inst.TargetStableId >= ArenaSession.ContenderStableIdBase) + { + targetEntityId = (int)(inst.TargetStableId - ArenaSession.ContenderStableIdBase); + } + + _netEvents.Add(new OrdnanceNetEvent( + inst.OrdnanceId, + inst.ParentOrdnanceId, + (byte)kind == (byte)OrdnanceEventKind.Spawned ? OrdnanceEventKind.Spawned : kind, + inst.ShooterStableId, + inst.IsSpectatorShooter, + shooterEntityId, + inst.WeaponKey, + inst.Def.DefIndex, + inst.Pos, + inst.Vel, + targetEntityId, + targetIsSpec, + _sink.State.Time, + (byte)inst.Def.VisualShape, + inst.Def.ColorRgba)); + } + + private static Vector3 ApplyPitchBias(Vector3 dir, float pitchDeg) + { + if (MathF.Abs(pitchDeg) < 0.01f) + { + return dir; + } + Vector3 right = Vector3.Cross(dir, Vector3.UnitY); + if (right.LengthSquared() < 1e-5f) + { + right = Vector3.UnitX; + } + else + { + right = Vector3.Normalize(right); + } + // Cross(dir, UnitY) with positive angle pitches upward (+Y) + float rad = pitchDeg * MathF.PI / 180f; + var q = Quaternion.CreateFromAxisAngle(right, rad); + Vector3 pitched = Vector3.Transform(dir, q); + return pitched.LengthSquared() > 1e-6f ? Vector3.Normalize(pitched) : Vector3.UnitY; + } + + private static Vector3 ApplySpread(Vector3 baseDir, float yawOffset, float pitchOffset) + { + var yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawOffset); + var rotated = Vector3.Transform(baseDir, yawQ); + var right = Vector3.Cross(rotated, Vector3.UnitY); + if (right.LengthSquared() > 1e-4f) + { + var pitchQ = Quaternion.CreateFromAxisAngle(Vector3.Normalize(right), pitchOffset); + rotated = Vector3.Transform(rotated, pitchQ); + } + return Vector3.Normalize(rotated); + } + + private static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadians) + { + float dot = Math.Clamp(Vector3.Dot(current, target), -1f, 1f); + float angle = MathF.Acos(dot); + if (angle <= maxRadians || angle < 1e-4f) + { + return target; + } + float t = maxRadians / angle; + Vector3 lerped = Vector3.Lerp(current, target, t); + return lerped.LengthSquared() > 1e-6f ? Vector3.Normalize(lerped) : target; + } + } +} diff --git a/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs b/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs new file mode 100644 index 0000000..99781f3 --- /dev/null +++ b/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs @@ -0,0 +1,660 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Numerics; +using MessagePack; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class OrdnanceAndProceduralWeaponTests + { + private static void IsolateContenders(ArenaSession session, params int[] keepIds) + { + var keep = keepIds.ToHashSet(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (!keep.Contains(c.Id)) + { + session.SetContenderPose(c.Id, -280f + i * 10f, -280f); + } + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, 280f, -280f + i * 4f); + } + } + + [Fact] + public void ProceduralWeapons_DeterministicGeneration_And12ByteKeyRoundTrip() + { + var rng = new Random(1337); + for (int i = 0; i < 200; i++) + { + byte mfg = (byte)(i % 5); + byte arch = (byte)(mfg * 4 + (i % 4)); + byte tier = (byte)(i % 4); + byte flags = (byte)(i % 2); + ulong seed = ((ulong)(uint)rng.Next() << 32) | (uint)rng.Next(); + + var key = new ProceduralWeaponKey(seed, mfg, arch, tier, flags); + var specA = ProceduralWeaponGenerator.Generate(key); + var specB = ProceduralWeaponGenerator.Generate(key); + + Assert.Equal(specA.DisplayName, specB.DisplayName); + Assert.Equal(specA.SummaryLine1, specB.SummaryLine1); + Assert.Equal(specA.SummaryLine2, specB.SummaryLine2); + Assert.Equal(specA.Assembly, specB.Assembly); + Assert.Equal(specA.PowerScore, specB.PowerScore); + Assert.Equal(specA.Module.WeaponDamage, specB.Module.WeaponDamage); + Assert.Equal(specA.FlattenedNodes.Length, specB.FlattenedNodes.Length); + for (int n = 0; n < specA.FlattenedNodes.Length; n++) + { + Assert.Equal(specA.FlattenedNodes[n].DefIndex, specB.FlattenedNodes[n].DefIndex); + Assert.Equal(specA.FlattenedNodes[n].Depth, specB.FlattenedNodes[n].Depth); + Assert.Equal(specA.FlattenedNodes[n].Motion, specB.FlattenedNodes[n].Motion); + } + + string encodedId = specA.Module.Id; + Assert.True(ProceduralWeaponGenerator.TryParseId(encodedId, out var parsedKey)); + Assert.Equal(key, parsedKey); + + var specC = ProceduralWeaponGenerator.Generate(parsedKey); + Assert.Equal(specA.Module.Id, specC.Module.Id); + Assert.Equal(specA.PowerScore, specC.PowerScore); + Assert.True(Catalog.TryGetModule(encodedId, out var resolvedMod)); + Assert.Equal(specA.Module.Id, resolvedMod.Id); + Assert.Equal(1, specA.Module.Width); + Assert.InRange(specA.Module.Height, 1, 2); + } + } + + [Fact] + public void All5Manufacturers_All20Archetypes_GenerateValidTreesAndTwoLineTooltips() + { + for (int m = 0; m < 5; m++) + { + for (int a = 0; a < 4; a++) + { + var arch = (WeaponArchetypeKind)(m * 4 + a); + var key = new ProceduralWeaponKey(0xCAFE0001UL + (ulong)(m * 4 + a), (byte)m, (byte)arch, Tier: 2, Flags: 0); + var spec = ProceduralWeaponGenerator.Generate(key); + + Assert.Equal((ManufacturerId)m, spec.Manufacturer); + Assert.Equal(arch, spec.Archetype); + Assert.False(string.IsNullOrWhiteSpace(spec.DisplayName)); + Assert.False(string.IsNullOrWhiteSpace(spec.SummaryLine1)); + Assert.False(string.IsNullOrWhiteSpace(spec.SummaryLine2)); + Assert.True(float.IsFinite(spec.PowerScore) && spec.PowerScore > 0f); + Assert.True(float.IsFinite(spec.Module.WeaponDamage) && spec.Module.WeaponDamage > 0f); + Assert.True(float.IsFinite(spec.Module.FireCooldown) && spec.Module.FireCooldown > 0f); + Assert.True(float.IsFinite(spec.Module.HeatOutput) && spec.Module.HeatOutput > 0f); + Assert.NotEmpty(spec.FlattenedNodes); + Assert.All(spec.FlattenedNodes, n => Assert.InRange(n.Depth, (byte)0, (byte)(OrdnanceNodeDef.MaxAllowedDepth - 1))); + Assert.InRange(spec.Assembly.ReceiverIdx, (byte)0, (byte)3); + Assert.InRange(spec.Assembly.BarrelIdx, (byte)0, (byte)3); + Assert.InRange(spec.Assembly.FeedIdx, (byte)0, (byte)3); + Assert.InRange(spec.Assembly.MuzzleIdx, (byte)0, (byte)3); + } + } + } + + [Fact] + public void DreamWeapon1_SabotRocketSled_TransitionsStageAt018s_AndHitsPointBlankWithoutTunneling() + { + // 1. Distant target (120m): Stage 0 Ballistic transitions at t=0.18s into Stage 1 RocketBoosted, accelerates >250m/s, impacts Anvil + crater + using (var session = new ArenaSession(seed: 101, slot0Human: true, skipInitialDrop: true)) + { + var shooter = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, target.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(target.Id, 0f, 120f, MathF.PI); + session.State.SpawnChassisDrop(0f, 120f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(target.Id)); + session.SetContenderPose(target.Id, 0f, 120f, MathF.PI); + target.AiScavengeCooldown = 999f; + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var sabotSled = ProceduralWeaponGenerator.CreateDreamSabotSled(); + Assert.True(shooter.Grid.TryMount(sabotSled.Module, "hp.weapon.siege_l")); + + // Settle one tick, then fire once + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 120f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + + float targetHpBefore = target.Grid.TotalArmorRatio() + target.Grid.CoreHp; + var events = new List(); + session.DrainStepEvents(events); // flush setup + + bool sawSpawned = false; + bool sawStageTransition = false; + float transitionMaxSpeed = 0f; + bool sawDetonated = false; + + for (int tick = 0; tick < 90; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + target.X, target.Z, + Fire: tick == 0, + InteractPickup: false, + Brake: true, + AimWorldY: MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight))); + session.Step(); + + foreach (ref readonly var inst in session.Ordnance.PoolSpan) + { + if (inst.Active && inst.Depth == 1) + { + transitionMaxSpeed = MathF.Max(transitionMaxSpeed, inst.Vel.Length()); + } + } + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Spawned) sawSpawned = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition) sawStageTransition = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Detonated) sawDetonated = true; + } + } + } + + float targetHpAfter = target.Grid.TotalArmorRatio() + target.Grid.CoreHp; + Assert.True(sawSpawned, "Expected Stage 0 Sabot-Sled Spawned event"); + Assert.True(sawStageTransition, "Expected Stage 0 -> Stage 1 StageTransition event at t=0.18s"); + Assert.True(transitionMaxSpeed > 250f, $"Expected Stage 1 RocketBoosted to accelerate >250 m/s, got {transitionMaxSpeed:F1}"); + Assert.True(sawDetonated, "Expected Sabot-Sled warhead detonation"); + Assert.True(targetHpAfter < targetHpBefore, "Expected distant Anvil to take Sabot-Sled damage"); + } + + // 2. Point-blank target (25m): Stage 0 impacts directly before 0.18s without StageTransition or tunneling + using (var session = new ArenaSession(seed: 102, slot0Human: true, skipInitialDrop: true)) + { + var shooter = session.State.Contenders[0]; + var target = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, target.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(target.Id, 0f, 25f, MathF.PI); + session.State.SpawnChassisDrop(0f, 25f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(target.Id)); + session.SetContenderPose(target.Id, 0f, 25f, MathF.PI); + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var sabotSled = ProceduralWeaponGenerator.CreateDreamSabotSled(); + Assert.True(shooter.Grid.TryMount(sabotSled.Module, "hp.weapon.siege_l")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 25f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + float hpBefore = target.Grid.TotalArmorRatio() + target.Grid.CoreHp; + bool sawStageTransition = false; + bool sawDetonated = false; + + for (int tick = 0; tick < 20; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + target.X, target.Z, + Fire: tick == 0, + InteractPickup: false, + Brake: true, + AimWorldY: MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight))); + session.Step(); + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition) sawStageTransition = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Detonated) sawDetonated = true; + } + } + } + + Assert.False(sawStageTransition, "Point-blank 25m shot should impact in Stage 0 before 0.18s transition"); + Assert.True(sawDetonated, "Expected Stage 0 sabot impact detonation at 25m"); + Assert.True(target.Grid.TotalArmorRatio() + target.Grid.CoreHp < hpBefore); + } + } + + [Fact] + public void DreamWeapon2_LoiteringLaserDrone_OrbitsFiresDownwardLasers_IgnoresNeutralSpectators_AndDiveBombs() + { + using var session = new ArenaSession(seed: 202, slot0Human: true, skipInitialDrop: true); + var shooter = session.State.Contenders[0]; + var enemy = session.State.Contenders[1]; + var neutralSpec = session.State.Spectators.Spectators[0]; + IsolateContenders(session, shooter.Id, enemy.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(enemy.Id, 0f, 55f, MathF.PI); + session.State.SpawnChassisDrop(0f, 55f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(enemy.Id)); + session.SetContenderPose(enemy.Id, 0f, 55f, MathF.PI); + + // Place a Neutral Spectator inside drone's 110m downward scan radius, well clear of 6m dive-bomb splash around enemy + session.SetSpectatorPose(neutralSpec.Id, 38f, 35f, 0f); + Assert.Equal(SpectatorStance.Neutral, neutralSpec.Stance); + float specHpBefore = neutralSpec.Grid.TotalArmorRatio() + neutralSpec.Grid.CoreHp; + + var droneLauncher = ProceduralWeaponGenerator.CreateDreamLoiteringDrone(); + Assert.True(shooter.Grid.TryMount(droneLauncher.Module, "hp.weapon.roof")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 55f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + float enemyHpBefore = enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp; + int stageTransitions = 0; + int downwardDroneLasers = 0; + bool sawDiveBombDetonation = false; + + for (int tick = 0; tick < 540; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + enemy.X, enemy.Z, + Fire: tick == 0, + InteractPickup: false, + Brake: true, + AimWorldY: enemy.Y + 2f)); + session.Step(); + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition) + { + stageTransitions++; + } + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Detonated) + { + sawDiveBombDetonation = true; + } + } + else if (ev is ShotFiredEvent shot && + shot.StartY > 12f && + shot.EndY < shot.StartY - 8f && + (WeaponVisualClass)shot.WeaponClass == WeaponVisualClass.ThermalBeam) + { + downwardDroneLasers++; + } + } + } + + Assert.True(stageTransitions >= 2, $"Expected >=2 stage transitions (climb->loiter->divebomb), got {stageTransitions}"); + Assert.True(downwardDroneLasers >= 6, $"Expected >=6 downward laser beams from loitering drone, got {downwardDroneLasers}"); + Assert.True(sawDiveBombDetonation, "Expected terminal HomingMissile dive-bomb detonation"); + Assert.True(enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp < enemyHpBefore, "Expected enemy Anvil to take laser + dive-bomb damage"); + Assert.Equal(SpectatorStance.Neutral, neutralSpec.Stance); + Assert.Equal(specHpBefore, neutralSpec.Grid.TotalArmorRatio() + neutralSpec.Grid.CoreHp); + } + + [Fact] + public void DreamWeapon3_MirvMineBlanket_SplitsIntoArmedMines_IgnoresOwner_DetonatesOnEnemy() + { + using var session = new ArenaSession(seed: 303, slot0Human: true, skipInitialDrop: true); + var shooter = session.State.Contenders[0]; + var enemy = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, enemy.Id); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(enemy.Id, 0f, 400f, MathF.PI); // keep enemy clear during deployment + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var mirvWeapon = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + Assert.True(shooter.Grid.TryMount(mirvWeapon.Module, "hp.weapon.siege_l")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 120f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + bool sawSplit = false; + int minesDeployed = 0; + + // Fire once toward (0, 120) and let carrier reach apex -> split -> land as armed mines + for (int tick = 0; tick < 240; tick++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + 0f, 120f, + Fire: tick == 0, + InteractPickup: false, + Brake: true)); + session.Step(); + + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one) + { + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.Split) sawSplit = true; + if ((OrdnanceEventKind)one.Kind == OrdnanceEventKind.StageTransition && + (OrdnanceVisualShape)one.VisualShape == OrdnanceVisualShape.Mine) + { + minesDeployed++; + } + } + } + } + + Assert.True(sawSplit, "Expected MIRV carrier to Split at apex"); + Assert.True(minesDeployed >= 8, $"Expected >=8 deployed StationaryMines, got {minesDeployed}"); + + // Pick a live armed mine position + Vector3 minePos = Vector3.Zero; + int activeMinesBeforeOwner = 0; + foreach (ref readonly var inst in session.Ordnance.PoolSpan) + { + if (inst.Active && inst.Def.Motion == OrdnanceMotion.StationaryMine) + { + activeMinesBeforeOwner++; + minePos = inst.Pos; + } + } + Assert.True(activeMinesBeforeOwner >= 8); + + // Shooter drives directly over own minefield -> ProximityIgnoreOwner must prevent detonation! + float shooterHpBefore = shooter.Grid.TotalArmorRatio() + shooter.Grid.CoreHp; + session.SetContenderPose(shooter.Id, minePos.X, minePos.Z, 0f); + for (int t = 0; t < 15; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, minePos.X, minePos.Z + 10f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + } + Assert.Equal(shooterHpBefore, shooter.Grid.TotalArmorRatio() + shooter.Grid.CoreHp); + + // Move shooter away, then place enemy contender right onto the mine -> must detonate and damage enemy! + session.SetContenderPose(shooter.Id, -100f, -100f, 0f); + float enemyHpBefore = enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp; + session.SetContenderPose(enemy.Id, minePos.X, minePos.Z, 0f); + events.Clear(); + session.DrainStepEvents(events); + + bool mineDetonated = false; + for (int t = 0; t < 10; t++) + { + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + if (events.OfType().Any(e => (OrdnanceEventKind)e.Kind == OrdnanceEventKind.Detonated)) + { + mineDetonated = true; + } + } + + Assert.True(mineDetonated, "Expected armed mine to detonate when enemy entered 6.5m proximity"); + Assert.True(enemy.Grid.TotalArmorRatio() + enemy.Grid.CoreHp < enemyHpBefore); + } + + [Fact] + public void SafetyCaps_12MirvSpamEnforces256PoolCapAndDepthUnder4_AndRejectsDepth5OrCycles() + { + // 1. Reject depth-5 chain (depth 4 node violates MaxAllowedDepth=4) + var d4 = new OrdnanceNodeDef { Motion = OrdnanceMotion.HitscanBeam }; + var d3 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d4 } } + }; + var d2 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d3 } } + }; + var d1 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d2 } } + }; + var d0 = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = d1 } } + }; + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(d0)); + + // 2. Reject cyclic graph + var cycleA = new OrdnanceNodeDef { Motion = OrdnanceMotion.Ballistic }; + var cycleB = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleA } } + }; + var cycleRoot = new OrdnanceNodeDef + { + Motion = OrdnanceMotion.Ballistic, + Triggers = new[] + { + new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleB } + } + }; + // Hook cycleA -> cycleRoot via reflection-free self-loop using array mutation + var aRules = new[] { new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleRoot } }; + var cycleSelf = new OrdnanceNodeDef { Motion = OrdnanceMotion.Ballistic, Triggers = aRules }; + aRules[0] = new OrdnanceTriggerRule { Kind = OrdnanceTriggerKind.Impact, Action = OrdnanceTriggerAction.Transition, ChildNode = cycleSelf }; + Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(cycleSelf)); + + // 3. 12 contenders firing MIRVs simultaneously for 600 ticks strictly obey ActiveCount <= 256 & MaxObservedDepth < 4 + using var session = new ArenaSession(seed: 404, slot0Human: false, skipInitialDrop: true); + var mirv = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + float ang = (i / 12f) * MathF.Tau; + session.SetContenderPose(c.Id, MathF.Cos(ang) * 140f, MathF.Sin(ang) * 140f, ang + MathF.PI); + session.State.SpawnChassisDrop(c.X, c.Z, Catalog.Anvil); + session.State.TrySwapNearbyChassis(c.Id); + session.SetContenderPose(c.Id, MathF.Cos(ang) * 140f, MathF.Sin(ang) * 140f, ang + MathF.PI); + c.Grid.TryMount(mirv.Module, "hp.weapon.siege_l"); + c.Grid.TryMount(mirv.Module, "hp.weapon.siege_r"); + } + + int maxObservedActive = 0; + for (int tick = 0; tick < 600; tick++) + { + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (c.IsGroundedActive) + { + c.AimX = 0f; + c.AimY = 4f; + c.AimZ = 0f; + c.FireCmd = true; + } + } + session.Step(); + maxObservedActive = Math.Max(maxObservedActive, session.Ordnance.ActiveCount); + Assert.InRange(session.Ordnance.ActiveCount, 0, OrdnanceRuntime.PoolCapacity); + Assert.True(session.Ordnance.MaxObservedDepth < OrdnanceNodeDef.MaxAllowedDepth); + } + + Assert.True(maxObservedActive > 64, $"Expected heavy concurrent MIRV saturation, peaked at {maxObservedActive}"); + } + + [Fact] + public void ZeroTunneling_400MetersPerSecondSabot_Hits1Point5MeterWallWithoutPassingThroughTargetBehind() + { + using var session = new ArenaSession(seed: 505, slot0Human: true, skipInitialDrop: true); + var shooter = session.State.Contenders[0]; + var targetBehindWall = session.State.Contenders[1]; + IsolateContenders(session, shooter.Id, targetBehindWall.Id); + + // Add a thin 1.5m-thick static wall directly in world between shooter (0, 0) and target (0, 50) + session.World.AddStaticBox( + 90UL, + (0f, 3.0f, 25f), + (12f, 6.0f, 0.75f), // 1.5m thick in Z! + friction: 0.4f, + restitution: 0.05f); + + session.SetContenderPose(shooter.Id, 0f, 0f, 0f); + session.SetContenderPose(targetBehindWall.Id, 0f, 50f, MathF.PI); + session.State.SpawnChassisDrop(0f, 50f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(targetBehindWall.Id)); + session.SetContenderPose(targetBehindWall.Id, 0f, 50f, MathF.PI); + + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis(shooter.Id)); + var gaussRail = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.HypervelocityGaussRail); + Assert.True(shooter.Grid.TryMount(gaussRail.Module, "hp.weapon.siege_l")); + + session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 50f, Fire: false, InteractPickup: false, Brake: true)); + session.Step(); + var events = new List(); + session.DrainStepEvents(events); + + float behindHpBefore = targetBehindWall.Grid.TotalArmorRatio() + targetBehindWall.Grid.CoreHp; + bool wallHitRecorded = false; + + for (int t = 0; t < 30; t++) + { + session.SetHumanInput(0, new PlayerInput( + 0f, 0f, + 0f, 50f, + Fire: t == 0, + InteractPickup: false, + Brake: true, + AimWorldY: shooter.Y)); + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is HitImpactEvent hit && hit.TargetKind == (byte)HitTargetKind.StaticCover && hit.TargetId == 90) + { + wallHitRecorded = true; + Assert.InRange(hit.HitZ, 24.0f, 26.0f); + } + } + } + + Assert.True(wallHitRecorded, "Expected 420m/s Gauss sabot to strike 1.5m-thick wall without tunneling"); + Assert.Equal(behindHpBefore, targetBehindWall.Grid.TotalArmorRatio() + targetBehindWall.Grid.CoreHp); + } + + [Fact] + public void AiPowerScore_EquipsMirvOverStarterMg762_AndNetUnion13ReplicatesUnder1152UdpCap() + { + // 1. AI PowerScore prefers MIRV Mine-Blanket over Mg762 + var state = new MatchState(seed: 606, skipInitialDrop: true); + var ai = state.Contenders[1]; + state.SpawnChassisDrop(ai.X, ai.Z, Catalog.Anvil); + Assert.True(state.TrySwapNearbyChassis(ai.Id)); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.siege_l")); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.siege_r")); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_l")); + Assert.True(ai.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r")); + + var mirv = ProceduralWeaponGenerator.CreateDreamMirvMineBlanket(); + ai.Grid.Cargo.Add(mirv.Module); + + MatchRules.UpdateAiContenders(state, 1f / 60f, (_, _, _, _, _, _) => true); + Assert.Contains(ai.Grid.Mounted, m => m.Spec.Id == mirv.Module.Id); + + // 2. [Union(13)] OrdnanceNodeEvent MessagePack round-trip & ServerMatchHost -> RemoteArenaSession PVS replication + var ordEv = new OrdnanceNodeEvent + { + OrdnanceId = 42, + ParentOrdnanceId = 7, + Kind = (byte)OrdnanceEventKind.StageTransition, + IsSpectatorShooter = false, + ShooterId = 0, + WeaponKey = mirv.Key, + NodeDefIndex = 1, + PosX = 10f, + PosY = 25f, + PosZ = 40f, + VelX = 0f, + VelY = 12f, + VelZ = 180f, + TargetEntityId = 1, + TargetIsSpectator = false, + SimTime = 4.25f, + VisualShape = (byte)OrdnanceVisualShape.Rocket, + ColorRgba = 0xF2C422FFu + }; + byte[] encoded = MessagePackSerializer.Serialize(ordEv); + var decoded = Assert.IsType(MessagePackSerializer.Deserialize(encoded)); + Assert.Equal(ordEv.OrdnanceId, decoded.OrdnanceId); + Assert.Equal(ordEv.WeaponKey, decoded.WeaponKey); + Assert.Equal(ordEv.ColorRgba, decoded.ColorRgba); + + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 707, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + using var client = new RemoteArenaSession(serverEp, "Client01"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(3); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(); + System.Threading.Thread.Sleep(2); + } + Assert.True(client.IsJoined); + + int cSlot = client.LocalContenderId; + int shooterSlot = (cSlot + 1) % MatchState.ContenderCount; + host.Session.SetContenderPose(shooterSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(cSlot, 0f, 20f, 0f); + host.Session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(host.Session.TrySwapNearbyChassis(shooterSlot)); + host.Session.State.Contenders[shooterSlot].Grid.TryMount(mirv.Module, "hp.weapon.siege_l"); + host.Session.SetContenderPose(shooterSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(cSlot, 0f, 20f, 0f); + + var clientEvents = new List(); + bool clientReceivedOrdnanceEvent = false; + for (int t = 0; t < 60; t++) + { + nowMs += 16; + var shooter = host.Session.State.Contenders[shooterSlot]; + shooter.AimX = 0f; + shooter.AimY = shooter.Y; + shooter.AimZ = 120f; + shooter.FireCmd = (t == 0); + host.StepOnce(nowMs); + client.PumpNetwork(); + client.BeginRenderFrame(1f / 60f, 1f); + clientEvents.Clear(); + client.DrainSimEvents(clientEvents); + if (clientEvents.OfType().Any()) + { + clientReceivedOrdnanceEvent = true; + break; + } + System.Threading.Thread.Sleep(2); + } + + Assert.True(clientReceivedOrdnanceEvent, "Expected remote client in PVS to receive [Union(13)] OrdnanceNodeEvent"); + } + } +}