From fcf1b4688031e4676faf2fa9cc193b8ce0ba7fa6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 17:22:51 +0200 Subject: [PATCH 1/8] AI pilots vent on a Track paint past half and overdrive to close (consumable-ai r3) Re-land on master of the h1 cut with the s1 fixes: the vent rule reads one Track paint in the ship's own IncomingPaints, TryActivateConsumable refuses on an inactive ship, the AI holds while a consumable of the kind is active, and the top of the lock strength range is pinned. Not yet built or run. Co-Authored-By: Claude Opus 5.5 --- .../ServerShared/Agents/States/Combat.cs | 29 ++ Assets/Scripts/ServerShared/Entity.cs | 12 + .../ConsumableAiTests.cs | 344 ++++++++++++++++++ .../Aetheria.Shared.Tests/LockWarningTests.cs | 3 +- 4 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 tests/Aetheria.Shared.Tests/ConsumableAiTests.cs diff --git a/Assets/Scripts/ServerShared/Agents/States/Combat.cs b/Assets/Scripts/ServerShared/Agents/States/Combat.cs index 3e143eb52..d7c20f275 100644 --- a/Assets/Scripts/ServerShared/Agents/States/Combat.cs +++ b/Assets/Scripts/ServerShared/Agents/States/Combat.cs @@ -10,6 +10,12 @@ using float2x2 = CultMath.float2x2; public class CombatState : BaseState { private const int DPS_SAMPLE_COUNT = 32; + // The Strength of one Track paint in this ship's own IncomingPaints: a fire-control emitter tracking this ship + // that hard (rulings lock-warning-strength, sensor-stat-set item 4, launcher-lock-solution-quality). + private const float LockAlarm = .5f; + // Overdrive only to close a target farther than this many optimum ranges, while heading within this many degrees of it. + private const float OverdriveRangeFactor = 2f; + private const float OverdriveArcDegrees = 15f; private float _optimumRange; private readonly List<(int index, float dps)> _availableGroups = new List<(int index, float dps)>(); private readonly List _availableLockingWeapons = new List(); @@ -78,6 +84,8 @@ public class CombatState : BaseState foreach(var w in _availableLockingWeapons) w.Activate(); + UseConsumables(toTarget, targetDistance); + var selectedGroup = -1; var maxDps = Single.MinValue; foreach (var group in _availableGroups) @@ -132,6 +140,27 @@ public class CombatState : BaseState // Fire charged guns! } + // The AI plays the player's rule on the player's information: vent when one Track paint on this ship passes half, + // otherwise overdrive to close a distant target ahead. It reads only this ship's own IncomingPaints. Both go + // through TryActivateConsumable, and a ship carrying neither does nothing. + private void UseConsumables(float3 toTarget, float targetDistance) + { + var ship = _agent.Ship; + if (ship.IncomingPaints.Any(p => p.Mode == PaintMode.Track && p.Strength > LockAlarm)) + Use(b => b is VapourDumpData); + else if (targetDistance > OverdriveRangeFactor * _optimumRange && + dot(normalize(ship.Direction), normalize(toTarget.xz)) > cos(radians(OverdriveArcDegrees))) + Use(b => b is ThrottleLockData); + } + + // One of a kind at a time: a Stackable design would otherwise be drained once per tick. + private void Use(Predicate kind) + { + if (_agent.Ship.HasActiveConsumable(kind)) return; + var consumable = _agent.Ship.FirstCarriedConsumable(kind); + if (consumable != null) _agent.Ship.TryActivateConsumable(consumable); + } + private void SampleDps() { var minRange = Single.MaxValue; diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 4d9470963..53af5d165 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1350,8 +1350,20 @@ public abstract class Entity return data.Stackable || FindActiveConsumable(data) == null; } + // The first consumable design in cargo with a behaviour of the asked kind, or null. Callers ask by kind, never + // by name: a design's name is a label and its behaviours are what it does. + public ConsumableItemData FirstCarriedConsumable(Predicate kind) => + CargoBays.SelectMany(bay => bay.Cargo.Keys).OfType() + .Select(item => ItemManager.GetData(item) as ConsumableItemData) + .FirstOrDefault(data => data != null && data.Behaviors.Any(b => kind(b))); + + public bool HasActiveConsumable(Predicate kind) => + _activeConsumables.Any(e => e.Data.Behaviors.Any(b => kind(b))); + public bool TryActivateConsumable(ConsumableItemData data) { + // Death and docking Remove and Deactivate the ship while its agent keeps ticking. + if (!_active) return false; if (!CanActivateConsumable(data)) return false; var key = ItemManager.ItemData.RefOf(data).Key; diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs new file mode 100644 index 000000000..7dc8b4ae1 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; + +// AI pilots use consumables (aetheria-release cut consumable-ai r3; rulings sensor-stat-set item 4, +// lock-warning-strength, launcher-lock-solution-quality): CombatState vents when ONE Track paint in the ship's own +// IncomingPaints passes .5 and otherwise overdrives to close a target farther than twice its optimum range while +// heading within 15 degrees of it. It reads only its own ship's senses. A consumable is chosen by what its behaviours +// are, never by name, so the vent design is named "Overdrive" and the overdrive design "Coolant". +// +// The agent's one gun has Range 1000 and EffectiveRange 500 with nothing at maximum range, so its optimum range is +// about 500 while its shortest and longest gun range are both 1000: a threshold taken from either gun range is wrong +// and these tests can tell. The optimum is read by reflection, as FireControlTests does, and the thresholds are +// authored against it. +public sealed class ConsumableAiTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-consumable-ai-" + Guid.NewGuid().ToString("N")); + private readonly List _caches = new List(); + private static readonly int2 HardpointCell = new int2(0, 0); + private static readonly int2 HoldCell = new int2(1, 1); + private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic; + + public ConsumableAiTests() => Directory.CreateDirectory(_root); + + public void Dispose() + { + foreach (var c in _caches) c.Dispose(); + Directory.Delete(_root, true); + } + + private static PerformanceStat Const(float v) => new PerformanceStat { Min = v, Max = v }; + + private sealed class Scene + { + public ItemManager Items; + public Zone Zone; + public Ship Agent, Prey, Locker; + public EquippedCargoBay Hold; + public ConsumableItemData Vent, Overdrive, Decoy, StackableVent; + public CultRecordRef Maker; + public float Optimum; + + public void Store(ConsumableItemData design) => + Assert.True(Hold.TryStore((ItemInstance) Items.CreateInstance(Items.CreateLot(design, Maker, .5f)))); + + public bool Active(ConsumableItemData design) => Agent.FindActiveConsumable(design) != null; + public int Carried => Hold.Cargo.Keys.Count(i => i is ConsumableItem); + + public object State => typeof(Agent).GetField("_currentState", Private).GetValue(Zone.Agents.Single()); + public void AssertInCombat() => Assert.True(State is CombatState, $"the agent is in {State?.GetType().Name}"); + + // The target at `distance` and `degrees` off the hull's heading, the agent at the origin heading (0, 1). + public void Place(float distance, float degrees) + { + Agent.Position = float3.zero; + Agent.Direction = float2(0, 1); + var a = degrees * 0.0174533f; + Prey.Position = float3(sin(a) * distance, 0, cos(a) * distance); + } + + // Paints of the locker's launcher reaching the agent as the zone publishes them, then one tick in which the + // agent decides. The agent reads them before the zone republishes (agents update, then PublishInbox). + public void Tick(params (PaintMode mode, float strength)[] paints) + { + foreach (var (mode, strength) in paints) + Agent.ReceivePaint(Locker, Locker.Equipment.Single(i => i.Behaviors.Any(b => b is LockWeapon)), mode, strength); + Agent.PublishInbox(); + Zone.Update(.05f); + } + } + + private static GearData GunData() => new GearData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = + { + new InstantWeaponData + { + Damage = Const(10), Range = Const(1000), MinRange = Const(0), Velocity = Const(0), + Spread = Const(0), DamageSpread = Const(0), Penetration = Const(0), Count = Const(1), + BurstTime = Const(0), Cooldown = Const(1), + EffectiveRange = Const(500), DamageAtMaxRange = 0f + } + } + }; + + private Scene Build(bool carryVent = false, bool carryOverdrive = false, bool carryDecoy = false, int stackableVents = 0) + { + var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true); + _caches.Add(cache); + cache.Upsert(new VerseGrammar { Revision = 1 }); + cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" }); + var hullShape = new Shape(3, 3); + foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true; + cache.Upsert(new HullData + { + Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 1000000, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() } } + }); + cache.Upsert(GunData()); + cache.Upsert(LockWarningTests.Launcher("Launcher", lockSpeed: .6f, sensorImpact: 1, lockAngle: 30, directionImpact: 1)); + var interior = new Shape(4, 1); + foreach (var cell in interior.AllCoordinates) interior[cell] = true; + cache.Upsert(new CargoBayData { Name = "Hold", Shape = new Shape(), InteriorShape = interior, Durability = 10 }); + // A vent named like the other kind, an overdrive named like it, a decoy, and a stackable vent. + cache.Upsert(new ConsumableItemData + { + Name = "Overdrive", Duration = 100f, Shape = new Shape(), + Behaviors = { new VapourDumpData { Radius = Const(20), Opacity = Const(.9f), Lifetime = Const(100) } } + }); + cache.Upsert(new ConsumableItemData { Name = "Coolant", Duration = 100f, Shape = new Shape(), Behaviors = { new ThrottleLockData() } }); + cache.Upsert(new ConsumableItemData { Name = "Flare", Duration = 1f, Shape = new Shape() }); + cache.Upsert(new ConsumableItemData + { + Name = "StackVent", Duration = 100f, Stackable = true, Shape = new Shape(), + Behaviors = { new VapourDumpData { Radius = Const(20), Opacity = Const(.9f), Lifetime = Const(100) } } + }); + cache.FlushAsync().Wait(); + + var settings = RunSaveTests.TestSettings(); + settings.TargetDetectionInfoThreshold = .1f; + settings.TargetGearInfoThreshold = .8f; + settings.FiringArc = 170; + settings.CommitHorizon = .5f; + settings.SchematicCellSize = 1f; + settings.UnaidedAccuracy = .05f; + settings.UnaidedTracking = 10f; + settings.UnaidedPrecision = 2f; + settings.AgentMinHitProbability = 0f; + settings.BeamResolveInterval = .1f; + var items = new ItemManager(cache, new ProvenanceLedger(), settings, _ => { }); + var maker = cache.RefOf(cache.GetByName("Maker")); + EquippableItem Make(string name) where T : CraftedItemData => + (EquippableItem) items.CreateInstance(items.CreateLot(cache.GetByName(name), maker, .5f)); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + Ship NewShip(string gear) + { + var ship = new Ship(items, zone, Make("Skiff"), new EntitySettings()) + { Faction = new Faction { Name = "F" + Guid.NewGuid().ToString("N") } }; + if (gear != null) Assert.True(ship.TryEquip(Make(gear), HardpointCell)); + return ship; + } + + var scene = new Scene + { + Items = items, Zone = zone, Maker = maker, + Vent = cache.GetByName("Overdrive"), + Overdrive = cache.GetByName("Coolant"), + Decoy = cache.GetByName("Flare"), + StackableVent = cache.GetByName("StackVent"), + Agent = NewShip("Gun"), Prey = NewShip(null), Locker = NewShip("Launcher") + }; + Assert.True(scene.Agent.TryEquip(Make("Hold"), HoldCell)); + scene.Hold = scene.Agent.CargoBays.Single(); + if (carryVent) scene.Store(scene.Vent); + if (carryOverdrive) scene.Store(scene.Overdrive); + if (carryDecoy) scene.Store(scene.Decoy); + for (var i = 0; i < stackableVents; i++) scene.Store(scene.StackableVent); + + // The agent is driven by a Minion added by hand; the locker is a gun ship nobody pilots. + zone.Admit(scene.Agent, piloted: false); + zone.Admit(scene.Prey, piloted: false); + zone.Admit(scene.Locker, piloted: false); + zone.Agents.Add(new Minion(scene.Agent)); + zone.Update(0f); // brings the gear online + scene.Agent.SetIff(scene.Prey, true); + scene.Agent.EntityInfoGathered[scene.Prey] = 1f; + scene.Agent.SetTarget(scene.Prey); + scene.Locker.Position = float3(0, 0, -40); + scene.Place(100f, 0f); + zone.Update(.05f); + zone.Update(.05f); + scene.AssertInCombat(); + + // The state sampled before the weapons' first stat evaluation: sample again over the live stats. + typeof(CombatState).GetMethod("SampleDps", Private).Invoke(scene.State, null); + scene.Optimum = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(scene.State); + Assert.InRange(scene.Optimum, 500f - 1000f / 32f, 500f + 1000f / 32f); + return scene; + } + + [Theory] + [InlineData(.4f, false)] + [InlineData(.49f, false)] + [InlineData(.5f, false)] + [InlineData(.51f, true)] + [InlineData(.6f, true)] + public void AnAgentVentsWhenLocked(float strength, bool vents) + { + var s = Build(carryVent: true, carryOverdrive: true); + s.AssertInCombat(); + + s.Tick((PaintMode.Track, strength)); + + Assert.Equal(vents, s.Active(s.Vent)); + Assert.Equal(vents ? 1 : 2, s.Carried); + Assert.False(s.Active(s.Overdrive)); + } + + [Fact] + public void AnAgentVentsOnOneTrackPaintOnItself() + { + var s = Build(carryVent: true); + s.AssertInCombat(); + + s.Tick((PaintMode.Track, .3f), (PaintMode.Track, .3f)); // two weak locks never sum + s.Tick((PaintMode.Search, .9f)); + s.Tick((PaintMode.Scan, .9f)); + Assert.False(s.Active(s.Vent)); + Assert.Equal(1, s.Carried); + + // The locker is a ship the agent has no information on, and one strong Track paint on it is enough. + s.Tick((PaintMode.Track, .9f)); + Assert.True(s.Active(s.Vent)); + Assert.Equal(0, s.Carried); + } + + // The production path: a real launcher on a ship the agent has never sensed locks it through zone ticks, and the + // agent vents once the paint is published, with its own senses as the only input. + [Fact] + public void AnUnseenLockerThatLocksTheAgentMakesItVent() + { + var s = Build(carryVent: true); + s.AssertInCombat(); + s.Locker.SetIff(s.Agent, true); + s.Locker.EntityInfoGathered[s.Agent] = 1f; + s.Locker.SetTarget(s.Agent); + + for (var i = 0; i < 4 && !s.Active(s.Vent); i++) + { + s.Place(100f, 0f); + s.Locker.Aim = normalize(s.Agent.Position - s.Locker.Position); + s.Zone.Update(1f); + } + + Assert.True(s.Active(s.Vent)); + Assert.Equal(0, s.Carried); + Assert.Equal(s.Prey, s.Agent.Target.Value.Entity); + } + + [Fact] + public void AnAgentThatIsLockedVentsInsteadOfOverdriving() + { + var s = Build(carryVent: true, carryOverdrive: true); + s.AssertInCombat(); + s.Place(3 * s.Optimum, 0f); + + s.Tick((PaintMode.Track, .6f)); + + Assert.True(s.Active(s.Vent)); + Assert.False(s.Active(s.Overdrive)); + Assert.Equal(1, s.Carried); + } + + [Theory] + [InlineData(0f, 2f, 20f, true)] + [InlineData(14f, 2f, 20f, true)] + [InlineData(16f, 2f, 20f, false)] + [InlineData(30f, 2f, 20f, false)] + [InlineData(180f, 2f, 20f, false)] + [InlineData(0f, 2f, -20f, false)] + [InlineData(0f, 1f, 0f, false)] + public void AnAgentOverdrivesToClose(float degrees, float optimums, float offset, bool overdrives) + { + var s = Build(carryVent: true, carryOverdrive: true); + s.AssertInCombat(); + s.Place(optimums * s.Optimum + offset, degrees); + + s.Tick(); + + Assert.Equal(overdrives, s.Active(s.Overdrive)); + Assert.False(s.Active(s.Vent)); + Assert.Equal(overdrives ? 1 : 2, s.Carried); + } + + [Fact] + public void AnOverdriveIsNotStoppedByAWeakTrackPaint() + { + var s = Build(carryVent: true, carryOverdrive: true); + s.AssertInCombat(); + s.Place(2 * s.Optimum + 20f, 0f); + + s.Tick((PaintMode.Track, .4f)); + + Assert.True(s.Active(s.Overdrive)); + Assert.False(s.Active(s.Vent)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AnAgentWithoutConsumablesDoesNothing(bool carryDecoy) + { + var s = Build(carryDecoy: carryDecoy); + s.AssertInCombat(); + + s.Tick((PaintMode.Track, .9f)); + s.Place(3 * s.Optimum, 0f); + s.Tick(); + + Assert.False(s.Active(s.Decoy)); + Assert.Equal(carryDecoy ? 1 : 0, s.Carried); + } + + [Fact] + public void ADeadOrDockedShipActivatesNothing() + { + var s = Build(carryVent: true, carryOverdrive: true); + s.AssertInCombat(); + Assert.True(s.Zone.Remove(s.Agent)); // what death and docking do + s.Agent.Deactivate(); + s.Place(3 * s.Optimum, 0f); + + s.Tick(); + s.Tick(); + + Assert.Equal(2, s.Carried); + Assert.False(s.Active(s.Vent)); + Assert.False(s.Active(s.Overdrive)); + Assert.False(s.Agent.TryActivateConsumable(s.Overdrive)); + Assert.Equal(2, s.Carried); + } + + [Fact] + public void AStackOfVentsIsSpentOneAtATime() + { + var s = Build(stackableVents: 3); + s.AssertInCombat(); + + s.Tick((PaintMode.Track, .6f)); + s.Tick((PaintMode.Track, .6f)); + s.Tick((PaintMode.Track, .6f)); + + Assert.True(s.Active(s.StackableVent)); + Assert.Equal(2, s.Carried); + } +} diff --git a/tests/Aetheria.Shared.Tests/LockWarningTests.cs b/tests/Aetheria.Shared.Tests/LockWarningTests.cs index 582a1b78f..18b068e63 100644 --- a/tests/Aetheria.Shared.Tests/LockWarningTests.cs +++ b/tests/Aetheria.Shared.Tests/LockWarningTests.cs @@ -67,7 +67,7 @@ public sealed class LockWarningTests : IDisposable private static PerformanceStat Const(float v) => new PerformanceStat { Min = v, Max = v }; - private static GearData Launcher(string name, float lockSpeed, float sensorImpact, float lockAngle, float directionImpact) => WithMunitionParts(new GearData + internal static GearData Launcher(string name, float lockSpeed, float sensorImpact, float lockAngle, float directionImpact) => WithMunitionParts(new GearData { Name = name, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, @@ -159,6 +159,7 @@ public sealed class LockWarningTests : IDisposable [InlineData(1.55f, .93f)] [InlineData(1.6f, .96f)] [InlineData(1.65f, .99f)] + [InlineData(1.66f, .996f)] public void StrengthIsTheLockAcrossItsWholeRange(float dt, float expectedLock) { var locker = NewShip(float3(0, 0, 0), "Launcher"); From f39ce7850ed8a815d2e2a284a9cbc120e9ad2bc8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 17:26:14 +0200 Subject: [PATCH 2/8] ConsumableAiTests: alias the CultMath vector types the static math import shadows --- tests/Aetheria.Shared.Tests/ConsumableAiTests.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index 7dc8b4ae1..c19375b19 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -7,6 +7,9 @@ using CultMath; using GameCult.Caching; using Xunit; using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; +using int2 = CultMath.int2; // AI pilots use consumables (aetheria-release cut consumable-ai r3; rulings sensor-stat-set item 4, // lock-warning-strength, launcher-lock-solution-quality): CombatState vents when ONE Track paint in the ship's own From 9b1ac4802784bc350ba0754d76ae5ba6a669ad53 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 17:29:20 +0200 Subject: [PATCH 3/8] ConsumableAiTests: assert the fixture carries what it stored --- tests/Aetheria.Shared.Tests/ConsumableAiTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index c19375b19..9117e7d91 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -166,6 +166,8 @@ public sealed class ConsumableAiTests : IDisposable if (carryOverdrive) scene.Store(scene.Overdrive); if (carryDecoy) scene.Store(scene.Decoy); for (var i = 0; i < stackableVents; i++) scene.Store(scene.StackableVent); + Assert.True(scene.Carried == (carryVent ? 1 : 0) + (carryOverdrive ? 1 : 0) + (carryDecoy ? 1 : 0) + stackableVents, + $"carried {scene.Carried}, cargo entries {scene.Hold.Cargo.Count}: {string.Join(",", scene.Hold.Cargo.Keys.Select(k => k.GetType().Name))}"); // The agent is driven by a Minion added by hand; the locker is a gun ship nobody pilots. zone.Admit(scene.Agent, piloted: false); From 2f1f392ecfc9202f36cfee393ec780e5641a0aa3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 17:30:32 +0200 Subject: [PATCH 4/8] ConsumableAiTests: stock the hold after the optimum is sampled --- tests/Aetheria.Shared.Tests/ConsumableAiTests.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index 9117e7d91..87b009244 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -162,13 +162,6 @@ public sealed class ConsumableAiTests : IDisposable }; Assert.True(scene.Agent.TryEquip(Make("Hold"), HoldCell)); scene.Hold = scene.Agent.CargoBays.Single(); - if (carryVent) scene.Store(scene.Vent); - if (carryOverdrive) scene.Store(scene.Overdrive); - if (carryDecoy) scene.Store(scene.Decoy); - for (var i = 0; i < stackableVents; i++) scene.Store(scene.StackableVent); - Assert.True(scene.Carried == (carryVent ? 1 : 0) + (carryOverdrive ? 1 : 0) + (carryDecoy ? 1 : 0) + stackableVents, - $"carried {scene.Carried}, cargo entries {scene.Hold.Cargo.Count}: {string.Join(",", scene.Hold.Cargo.Keys.Select(k => k.GetType().Name))}"); - // The agent is driven by a Minion added by hand; the locker is a gun ship nobody pilots. zone.Admit(scene.Agent, piloted: false); zone.Admit(scene.Prey, piloted: false); @@ -188,6 +181,14 @@ public sealed class ConsumableAiTests : IDisposable typeof(CombatState).GetMethod("SampleDps", Private).Invoke(scene.State, null); scene.Optimum = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(scene.State); Assert.InRange(scene.Optimum, 500f - 1000f / 32f, 500f + 1000f / 32f); + + // Stocked only now: before the first stat evaluation the optimum reads 0 and any target looks distant. + if (carryVent) scene.Store(scene.Vent); + if (carryOverdrive) scene.Store(scene.Overdrive); + if (carryDecoy) scene.Store(scene.Decoy); + for (var i = 0; i < stackableVents; i++) scene.Store(scene.StackableVent); + Assert.True(scene.Carried == (carryVent ? 1 : 0) + (carryOverdrive ? 1 : 0) + (carryDecoy ? 1 : 0) + stackableVents, + $"carried {scene.Carried}, cargo entries {scene.Hold.Cargo.Count}: {string.Join(",", scene.Hold.Cargo.Keys.Select(k => k.GetType().Name))}"); return scene; } From bf32a82e3239ab2baff658bc613b406cfb676365 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 19:03:50 +0200 Subject: [PATCH 5/8] CombatState derives its optimum range once the weapons' stats are known, and re-derives on loadout change A zone-spawned ship's CombatState sampled in its constructor, before any weapon had evaluated its stats, so the optimum range read 0 and never moved. It now marks the optimum stale on construction, on any equipment add/remove and on a weapon's online change, and samples at the next Update once every active weapon reports StatsKnown. ConsumableAiTests build the agent through Zone.Admit(piloted: true) and read the optimum without re-sampling; new rows pin the hold scope, hull-heading source, mixed paints, sight independence and the optimum across two guns and a refit. Not yet verified. Co-Authored-By: Claude Opus 5.5 --- .../ServerShared/Agents/States/Combat.cs | 23 ++- .../Scripts/ServerShared/Behaviors/Weapon.cs | 4 + .../ConsumableAiTests.cs | 168 +++++++++++++++--- 3 files changed, 166 insertions(+), 29 deletions(-) diff --git a/Assets/Scripts/ServerShared/Agents/States/Combat.cs b/Assets/Scripts/ServerShared/Agents/States/Combat.cs index d7c20f275..3e10a6d2a 100644 --- a/Assets/Scripts/ServerShared/Agents/States/Combat.cs +++ b/Assets/Scripts/ServerShared/Agents/States/Combat.cs @@ -17,20 +17,33 @@ public class CombatState : BaseState private const float OverdriveRangeFactor = 2f; private const float OverdriveArcDegrees = 15f; private float _optimumRange; + private bool _optimumStale = true; private readonly List<(int index, float dps)> _availableGroups = new List<(int index, float dps)>(); private readonly List _availableLockingWeapons = new List(); public CombatState(Agent agent) : base(agent) { - SampleDps(); - foreach (var weapon in _agent.Ship.Weapons) - { - weapon.Item.Online.Subscribe(b => SampleDps()); - } + foreach (var item in _agent.Ship.Equipment) Watch(item); + _agent.Ship.Equipment.ObserveAdd().Subscribe(add => { Watch(add.Value); _optimumStale = true; }); + _agent.Ship.Equipment.ObserveRemove().Subscribe(_ => _optimumStale = true); + } + + // The optimum is a function of the loadout's evaluated stats, so it is re-derived whenever a weapon comes or goes + // or changes online state, and only once every weapon that can run has evaluated its stats (a weapon evaluates on + // its first active tick, after it comes online): a ship the zone just spawned samples over live stats, not zeros. + private void Watch(EquippedItem item) + { + if (item.Behaviors.OfType().Any()) item.Online.Subscribe(_ => _optimumStale = true); } public override void Update(float delta) { + if (_optimumStale && _agent.Ship.Weapons.All(w => w.StatsKnown || !w.Item.Active.Value)) + { + SampleDps(); + _optimumStale = false; + } + var target = _agent.Ship.Target.Value.Entity; if (target == null) return; diff --git a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs index 6a01f81ca..05edbb887 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs @@ -173,9 +173,13 @@ public abstract class Weapon : Behavior, IActivatedBehavior Tracking = Evaluate(_data.Tracking); } + // False until the first active tick has evaluated the stats above: before it they all read zero. + public bool StatsKnown { get; private set; } + public override bool Execute(float dt) { UpdateStats(); + StatsKnown = true; return true; } diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index 87b009244..57418fea0 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -46,6 +46,7 @@ public sealed class ConsumableAiTests : IDisposable public Ship Agent, Prey, Locker; public EquippedCargoBay Hold; public ConsumableItemData Vent, Overdrive, Decoy, StackableVent; + public GearData LongGun; public CultRecordRef Maker; public float Optimum; @@ -58,11 +59,12 @@ public sealed class ConsumableAiTests : IDisposable public object State => typeof(Agent).GetField("_currentState", Private).GetValue(Zone.Agents.Single()); public void AssertInCombat() => Assert.True(State is CombatState, $"the agent is in {State?.GetType().Name}"); - // The target at `distance` and `degrees` off the hull's heading, the agent at the origin heading (0, 1). - public void Place(float distance, float degrees) + // The target at `distance` and `degrees` off north, the agent at the origin with its hull `hullDegrees` off north. + public void Place(float distance, float degrees, float hullDegrees = 0f) { Agent.Position = float3.zero; - Agent.Direction = float2(0, 1); + var h = hullDegrees * 0.0174533f; + Agent.Direction = float2(sin(h), cos(h)); var a = degrees * 0.0174533f; Prey.Position = float3(sin(a) * distance, 0, cos(a) * distance); } @@ -78,9 +80,9 @@ public sealed class ConsumableAiTests : IDisposable } } - private static GearData GunData() => new GearData + private static GearData GunData(float effective, string name = "Gun") => new GearData { - Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + Name = name, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, Behaviors = { @@ -89,12 +91,12 @@ public sealed class ConsumableAiTests : IDisposable Damage = Const(10), Range = Const(1000), MinRange = Const(0), Velocity = Const(0), Spread = Const(0), DamageSpread = Const(0), Penetration = Const(0), Count = Const(1), BurstTime = Const(0), Cooldown = Const(1), - EffectiveRange = Const(500), DamageAtMaxRange = 0f + EffectiveRange = Const(effective), DamageAtMaxRange = 0f } } }; - private Scene Build(bool carryVent = false, bool carryOverdrive = false, bool carryDecoy = false, int stackableVents = 0) + private Scene Build(bool carryVent = false, bool carryOverdrive = false, bool carryDecoy = false, int stackableVents = 0, float effective = 500f) { var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true); _caches.Add(cache); @@ -107,7 +109,8 @@ public sealed class ConsumableAiTests : IDisposable Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 1000000, Mass = 1000, Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() } } }); - cache.Upsert(GunData()); + cache.Upsert(GunData(effective)); + cache.Upsert(GunData(800f, "LongGun")); cache.Upsert(LockWarningTests.Launcher("Launcher", lockSpeed: .6f, sensorImpact: 1, lockAngle: 30, directionImpact: 1)); var interior = new Shape(4, 1); foreach (var cell in interior.AllCoordinates) interior[cell] = true; @@ -158,15 +161,16 @@ public sealed class ConsumableAiTests : IDisposable Overdrive = cache.GetByName("Coolant"), Decoy = cache.GetByName("Flare"), StackableVent = cache.GetByName("StackVent"), + LongGun = cache.GetByName("LongGun"), Agent = NewShip("Gun"), Prey = NewShip(null), Locker = NewShip("Launcher") }; Assert.True(scene.Agent.TryEquip(Make("Hold"), HoldCell)); scene.Hold = scene.Agent.CargoBays.Single(); - // The agent is driven by a Minion added by hand; the locker is a gun ship nobody pilots. - zone.Admit(scene.Agent, piloted: false); + // The agent joins as the zone admits a piloted ship (its Minion and CombatState come from production); the + // locker is a gun ship nobody pilots. + zone.Admit(scene.Agent, piloted: true); zone.Admit(scene.Prey, piloted: false); zone.Admit(scene.Locker, piloted: false); - zone.Agents.Add(new Minion(scene.Agent)); zone.Update(0f); // brings the gear online scene.Agent.SetIff(scene.Prey, true); scene.Agent.EntityInfoGathered[scene.Prey] = 1f; @@ -177,12 +181,10 @@ public sealed class ConsumableAiTests : IDisposable zone.Update(.05f); scene.AssertInCombat(); - // The state sampled before the weapons' first stat evaluation: sample again over the live stats. - typeof(CombatState).GetMethod("SampleDps", Private).Invoke(scene.State, null); + // Read, never re-sampled: the optimum is whatever production derived for the spawned ship. scene.Optimum = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(scene.State); - Assert.InRange(scene.Optimum, 500f - 1000f / 32f, 500f + 1000f / 32f); + Assert.InRange(scene.Optimum, effective - 1000f / 32f, effective + 1000f / 32f); - // Stocked only now: before the first stat evaluation the optimum reads 0 and any target looks distant. if (carryVent) scene.Store(scene.Vent); if (carryOverdrive) scene.Store(scene.Overdrive); if (carryDecoy) scene.Store(scene.Decoy); @@ -265,17 +267,24 @@ public sealed class ConsumableAiTests : IDisposable Assert.Equal(1, s.Carried); } + // Two guns, optimums about 300 and 700: the threshold is twice the optimum the ship derived, so no constant, no gun + // range and no scaling of the arc by distance can sit at 2 x optimum +- 20 for both. [Theory] - [InlineData(0f, 2f, 20f, true)] - [InlineData(14f, 2f, 20f, true)] - [InlineData(16f, 2f, 20f, false)] - [InlineData(30f, 2f, 20f, false)] - [InlineData(180f, 2f, 20f, false)] - [InlineData(0f, 2f, -20f, false)] - [InlineData(0f, 1f, 0f, false)] - public void AnAgentOverdrivesToClose(float degrees, float optimums, float offset, bool overdrives) + [InlineData(300f, 0f, 2f, 20f, true)] + [InlineData(300f, 14f, 2f, 20f, true)] + [InlineData(300f, 16f, 2f, 20f, false)] + [InlineData(300f, 30f, 2f, 20f, false)] + [InlineData(300f, 180f, 2f, 20f, false)] + [InlineData(300f, 0f, 2f, -20f, false)] + [InlineData(300f, 0f, 1f, 0f, false)] + [InlineData(700f, 0f, 2f, 20f, true)] + [InlineData(700f, 14f, 2f, 20f, true)] + [InlineData(700f, 16f, 2f, 20f, false)] + [InlineData(700f, 0f, 2f, -20f, false)] + [InlineData(700f, 0f, 1f, 0f, false)] + public void AnAgentOverdrivesToClose(float effective, float degrees, float optimums, float offset, bool overdrives) { - var s = Build(carryVent: true, carryOverdrive: true); + var s = Build(carryVent: true, carryOverdrive: true, effective: effective); s.AssertInCombat(); s.Place(optimums * s.Optimum + offset, degrees); @@ -286,6 +295,80 @@ public sealed class ConsumableAiTests : IDisposable Assert.Equal(overdrives ? 1 : 2, s.Carried); } + // The arc is the hull's heading against the bearing to the target; the aim always points at the target, so an + // arc taken from the aim would surge with the hull pointing away. + [Theory] + [InlineData(0f, 14f, true)] + [InlineData(0f, -14f, true)] + [InlineData(0f, 16f, false)] + [InlineData(0f, 90f, false)] + public void TheArcIsTheHullsHeadingNotTheAim(float targetDegrees, float hullDegrees, bool overdrives) + { + var s = Build(carryOverdrive: true); + s.AssertInCombat(); + s.Place(3 * s.Optimum, targetDegrees, hullDegrees); + + s.Tick(); + + Assert.Equal(overdrives, s.Active(s.Overdrive)); + } + + // The production path for the optimum: a ship the zone admits as piloted derives it from its gun's live stats + // before it needs it, and re-derives it when its loadout changes. The gun's effective range is 500 and the + // refitted gun's is 800, so the optimum moves with the weapons it has now. + [Fact] + public void ASpawnedShipsOptimumFollowsItsWeaponsAndNeverReadsZero() + { + var s = Build(carryOverdrive: true); + s.AssertInCombat(); + Assert.InRange(s.Optimum, 500f - 1000f / 32f, 500f + 1000f / 32f); + s.Place(30f, 0f); + + s.Tick(); + s.Tick(); + + Assert.False(s.Active(s.Overdrive)); // 30 m is not "distant" against a derived optimum + Assert.Equal(1, s.Carried); + + var longGun = (EquippableItem) s.Items.CreateInstance(s.Items.CreateLot(s.LongGun, s.Maker, .5f)); + Assert.NotNull(s.Agent.TryUnequip(s.Agent.Equipment.Single(e => e.Behaviors.OfType().Any()))); + Assert.True(s.Agent.TryEquip(longGun, HardpointCell)); + s.Zone.Update(.05f); + s.Zone.Update(.05f); + var refit = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(s.State); + Assert.NotEqual(s.Optimum, refit); + Assert.InRange(refit, 800f - 1000f / 32f, 800f + 1000f / 32f); + } + + // A Search or Scan paint and a Track paint in one tick, in either order: the strongest Track paint decides. + [Theory] + [InlineData(PaintMode.Search, PaintMode.Track)] + [InlineData(PaintMode.Track, PaintMode.Search)] + [InlineData(PaintMode.Scan, PaintMode.Track)] + [InlineData(PaintMode.Track, PaintMode.Scan)] + public void AMixOfPaintsInOneTickVentsOnTheTrackPaint(PaintMode first, PaintMode second) + { + var s = Build(carryVent: true); + s.AssertInCombat(); + + s.Tick((first, first == PaintMode.Track ? .9f : .2f), (second, second == PaintMode.Track ? .9f : .2f)); + + Assert.True(s.Active(s.Vent)); + Assert.Equal(0, s.Carried); + } + + [Fact] + public void AMixOfWeakTrackAndStrongSearchPaintsDoesNotVent() + { + var s = Build(carryVent: true); + s.AssertInCombat(); + + s.Tick((PaintMode.Search, .9f), (PaintMode.Track, .3f)); + s.Tick((PaintMode.Track, .3f), (PaintMode.Scan, .9f)); + + Assert.False(s.Active(s.Vent)); + } + [Fact] public void AnOverdriveIsNotStoppedByAWeakTrackPaint() { @@ -347,4 +430,41 @@ public sealed class ConsumableAiTests : IDisposable Assert.True(s.Active(s.StackableVent)); Assert.Equal(2, s.Carried); } + + // The hold is per kind: a second vent design in cargo is not spent while one vent is active, and an active + // overdrive does not stop a vent. + [Fact] + public void TheHoldIsPerKindNotPerDesignAndNotPerAnyConsumable() + { + var s = Build(carryVent: true, carryOverdrive: true, stackableVents: 1); + s.AssertInCombat(); + s.Place(3 * s.Optimum, 0f); + s.Tick(); // overdrive + Assert.True(s.Active(s.Overdrive)); + + s.Tick((PaintMode.Track, .6f)); + s.Tick((PaintMode.Track, .6f)); + s.Tick((PaintMode.Track, .6f)); + + Assert.True(s.Active(s.Overdrive)); + Assert.Equal(1, new[] { s.Vent, s.StackableVent }.Count(s.Active)); // one vent, whichever design came first + Assert.Equal(1, s.Carried); // the other vent design is still in cargo + } + + // The vent reads only the agent's own paints: with its target gone from VisibleEnemies (still targeted, no + // longer sensed) and the locker unseen, it still vents. + [Fact] + public void AVentDoesNotNeedAnyEnemyInSight() + { + var s = Build(carryVent: true); + s.AssertInCombat(); + s.Agent.VisibleEnemies.Clear(); + Assert.Equal(s.Prey, s.Agent.Target.Value.Entity); + Assert.DoesNotContain(s.Locker, s.Agent.VisibleEnemies); + + s.Tick((PaintMode.Track, .9f)); + + Assert.Empty(s.Agent.VisibleEnemies); + Assert.True(s.Active(s.Vent)); + } } From 99333cf1a2f405c26ef9eda49e2cf1c7d6e26a93 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 19:04:58 +0200 Subject: [PATCH 6/8] ConsumableAiTests: the admitted agent has no patrol task (the test zone has no orbits) Not yet verified. Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/ConsumableAiTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index 57418fea0..9c972a26e 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -169,6 +169,7 @@ public sealed class ConsumableAiTests : IDisposable // The agent joins as the zone admits a piloted ship (its Minion and CombatState come from production); the // locker is a gun ship nobody pilots. zone.Admit(scene.Agent, piloted: true); + zone.Agents.Single().Task = null; // the test zone has no orbits to patrol; the Minion and its CombatState are production's zone.Admit(scene.Prey, piloted: false); zone.Admit(scene.Locker, piloted: false); zone.Update(0f); // brings the gear online From 7e92c7da93c04844b274ed3c9a30599ee799f4a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 19:08:59 +0200 Subject: [PATCH 7/8] ConsumableAiTests: refit the gun the way a docked ship does Not yet verified. Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/ConsumableAiTests.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index 9c972a26e..adc8903bb 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -332,8 +332,12 @@ public sealed class ConsumableAiTests : IDisposable Assert.Equal(1, s.Carried); var longGun = (EquippableItem) s.Items.CreateInstance(s.Items.CreateLot(s.LongGun, s.Maker, .5f)); + Assert.True(s.Zone.Remove(s.Agent)); // refitting is a docked ship's act: out of the zone and inactive + s.Agent.Deactivate(); Assert.NotNull(s.Agent.TryUnequip(s.Agent.Equipment.Single(e => e.Behaviors.OfType().Any()))); Assert.True(s.Agent.TryEquip(longGun, HardpointCell)); + s.Zone.Admit(s.Agent, piloted: false); // back in, the agent's Minion keeps its CombatState + s.Place(30f, 0f); s.Zone.Update(.05f); s.Zone.Update(.05f); var refit = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(s.State); From 1e9a89e401e4b6157647d01b8b0425f4a632726c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 16 Oct 2026 19:28:29 +0200 Subject: [PATCH 8/8] CombatState: drop the StatsKnown gate; a stale optimum is re-derived at the next agent Update Agents update before the entities, so a weapon that came online this tick has evaluated by the next Update; the Weapon.StatsKnown flag and the gate on it were dead machinery and are removed. The add handler no longer marks stale itself (a new item's Online subscription does). The refit test fits and removes a dominating gun. Not yet verified. Co-Authored-By: Claude Opus 5.5 --- .../ServerShared/Agents/States/Combat.cs | 11 ++-- .../Scripts/ServerShared/Behaviors/Weapon.cs | 4 -- .../ConsumableAiTests.cs | 56 ++++++++++++------- 3 files changed, 43 insertions(+), 28 deletions(-) diff --git a/Assets/Scripts/ServerShared/Agents/States/Combat.cs b/Assets/Scripts/ServerShared/Agents/States/Combat.cs index 3e10a6d2a..42f04e3cd 100644 --- a/Assets/Scripts/ServerShared/Agents/States/Combat.cs +++ b/Assets/Scripts/ServerShared/Agents/States/Combat.cs @@ -24,13 +24,14 @@ public class CombatState : BaseState public CombatState(Agent agent) : base(agent) { foreach (var item in _agent.Ship.Equipment) Watch(item); - _agent.Ship.Equipment.ObserveAdd().Subscribe(add => { Watch(add.Value); _optimumStale = true; }); + _agent.Ship.Equipment.ObserveAdd().Subscribe(add => Watch(add.Value)); _agent.Ship.Equipment.ObserveRemove().Subscribe(_ => _optimumStale = true); } - // The optimum is a function of the loadout's evaluated stats, so it is re-derived whenever a weapon comes or goes - // or changes online state, and only once every weapon that can run has evaluated its stats (a weapon evaluates on - // its first active tick, after it comes online): a ship the zone just spawned samples over live stats, not zeros. + // The optimum is a function of the loadout's evaluated stats, so it is re-derived at the next Update (agents update + // before the entities, so by then the weapons that came online this tick have evaluated) whenever a weapon is + // added, removed or changes online state. Sampling on the event itself would read the stats before they exist: a + // ship the zone just spawned would keep an optimum of 0. private void Watch(EquippedItem item) { if (item.Behaviors.OfType().Any()) item.Online.Subscribe(_ => _optimumStale = true); @@ -38,7 +39,7 @@ public class CombatState : BaseState public override void Update(float delta) { - if (_optimumStale && _agent.Ship.Weapons.All(w => w.StatsKnown || !w.Item.Active.Value)) + if (_optimumStale) { SampleDps(); _optimumStale = false; diff --git a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs index 05edbb887..6a01f81ca 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs @@ -173,13 +173,9 @@ public abstract class Weapon : Behavior, IActivatedBehavior Tracking = Evaluate(_data.Tracking); } - // False until the first active tick has evaluated the stats above: before it they all read zero. - public bool StatsKnown { get; private set; } - public override bool Execute(float dt) { UpdateStats(); - StatsKnown = true; return true; } diff --git a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs index adc8903bb..ca1081585 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableAiTests.cs @@ -26,6 +26,7 @@ public sealed class ConsumableAiTests : IDisposable private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-consumable-ai-" + Guid.NewGuid().ToString("N")); private readonly List _caches = new List(); private static readonly int2 HardpointCell = new int2(0, 0); + private static readonly int2 SecondHardpointCell = new int2(2, 2); private static readonly int2 HoldCell = new int2(1, 1); private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic; @@ -46,7 +47,7 @@ public sealed class ConsumableAiTests : IDisposable public Ship Agent, Prey, Locker; public EquippedCargoBay Hold; public ConsumableItemData Vent, Overdrive, Decoy, StackableVent; - public GearData LongGun; + public GearData HeavyGun; public CultRecordRef Maker; public float Optimum; @@ -80,7 +81,7 @@ public sealed class ConsumableAiTests : IDisposable } } - private static GearData GunData(float effective, string name = "Gun") => new GearData + private static GearData GunData(float effective, string name = "Gun", float damage = 10f) => new GearData { Name = name, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, @@ -88,7 +89,7 @@ public sealed class ConsumableAiTests : IDisposable { new InstantWeaponData { - Damage = Const(10), Range = Const(1000), MinRange = Const(0), Velocity = Const(0), + Damage = Const(damage), Range = Const(1000), MinRange = Const(0), Velocity = Const(0), Spread = Const(0), DamageSpread = Const(0), Penetration = Const(0), Count = Const(1), BurstTime = Const(0), Cooldown = Const(1), EffectiveRange = Const(effective), DamageAtMaxRange = 0f @@ -107,10 +108,14 @@ public sealed class ConsumableAiTests : IDisposable cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 1000000, Mass = 1000, - Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() } } + Hardpoints = + { + new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() }, + new HardpointData { Type = HardpointType.Sensors, Position = SecondHardpointCell, Shape = new Shape() } + } }); cache.Upsert(GunData(effective)); - cache.Upsert(GunData(800f, "LongGun")); + cache.Upsert(GunData(800f, "HeavyGun", damage: 1000f)); cache.Upsert(LockWarningTests.Launcher("Launcher", lockSpeed: .6f, sensorImpact: 1, lockAngle: 30, directionImpact: 1)); var interior = new Shape(4, 1); foreach (var cell in interior.AllCoordinates) interior[cell] = true; @@ -161,7 +166,7 @@ public sealed class ConsumableAiTests : IDisposable Overdrive = cache.GetByName("Coolant"), Decoy = cache.GetByName("Flare"), StackableVent = cache.GetByName("StackVent"), - LongGun = cache.GetByName("LongGun"), + HeavyGun = cache.GetByName("HeavyGun"), Agent = NewShip("Gun"), Prey = NewShip(null), Locker = NewShip("Launcher") }; Assert.True(scene.Agent.TryEquip(Make("Hold"), HoldCell)); @@ -316,7 +321,7 @@ public sealed class ConsumableAiTests : IDisposable // The production path for the optimum: a ship the zone admits as piloted derives it from its gun's live stats // before it needs it, and re-derives it when its loadout changes. The gun's effective range is 500 and the - // refitted gun's is 800, so the optimum moves with the weapons it has now. + // heavy gun's is 800, so the optimum moves with the weapons it has now. [Fact] public void ASpawnedShipsOptimumFollowsItsWeaponsAndNeverReadsZero() { @@ -331,18 +336,31 @@ public sealed class ConsumableAiTests : IDisposable Assert.False(s.Active(s.Overdrive)); // 30 m is not "distant" against a derived optimum Assert.Equal(1, s.Carried); - var longGun = (EquippableItem) s.Items.CreateInstance(s.Items.CreateLot(s.LongGun, s.Maker, .5f)); - Assert.True(s.Zone.Remove(s.Agent)); // refitting is a docked ship's act: out of the zone and inactive - s.Agent.Deactivate(); - Assert.NotNull(s.Agent.TryUnequip(s.Agent.Equipment.Single(e => e.Behaviors.OfType().Any()))); - Assert.True(s.Agent.TryEquip(longGun, HardpointCell)); - s.Zone.Admit(s.Agent, piloted: false); // back in, the agent's Minion keeps its CombatState - s.Place(30f, 0f); - s.Zone.Update(.05f); - s.Zone.Update(.05f); - var refit = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(s.State); - Assert.NotEqual(s.Optimum, refit); - Assert.InRange(refit, 800f - 1000f / 32f, 800f + 1000f / 32f); + // A refit is a docked ship's act: out of the zone and inactive, then back in. The heavy gun dominates the + // damage, so with it fitted the optimum sits at its effective range, and without it at the first gun's. + void Refit(Action fit) + { + Assert.True(s.Zone.Remove(s.Agent)); + s.Agent.Deactivate(); + fit(s.Agent); + s.Zone.Admit(s.Agent, piloted: false); // back in, the agent's Minion keeps its CombatState + s.Place(30f, 0f); + s.Zone.Update(.05f); + s.Zone.Update(.05f); + } + float Optimum() => (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(s.State); + + EquippedItem heavy = null; + Refit(ship => + { + var before = ship.Equipment.ToList(); + Assert.True(ship.TryEquip((EquippableItem) s.Items.CreateInstance(s.Items.CreateLot(s.HeavyGun, s.Maker, .5f)), SecondHardpointCell)); + heavy = ship.Equipment.Single(e => !before.Contains(e)); + }); + Assert.InRange(Optimum(), 800f - 1000f / 32f, 800f + 1000f / 32f); + + Refit(ship => Assert.NotNull(ship.TryUnequip(heavy))); + Assert.InRange(Optimum(), 500f - 1000f / 32f, 500f + 1000f / 32f); } // A Search or Scan paint and a Track paint in one tick, in either order: the strongest Track paint decides.