Merge fire control Cut 2: targeting subsystem and subsystem reveal

A new interior Tool behaviour carrying accuracy, resolution, precision and
tracking; unaided fire falls back to one authored setting. The two info
thresholds are finally read: a target's equipment reveals as target data
accumulates, and one predicate and one writer serve both the player and
the AI when aiming at a revealed subsystem.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-19 13:04:43 +02:00
commit 3cf4603475
14 changed files with 702 additions and 5 deletions

View file

@ -68,6 +68,15 @@
"interactions": "",
"initialStateCheck": false
},
{
"name": "Cycle Target Item",
"type": "Button",
"id": "3f9a2f0a-6e3f-4a53-9f5e-1a9c1e6d9f7b",
"expectedControlType": "Button",
"processors": "",
"interactions": "",
"initialStateCheck": false
},
{
"name": "Toggle Heatsinks",
"type": "Button",
@ -307,6 +316,17 @@
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "8c2d5e77-4b18-4f0b-9a2e-6d3f7c1a5e90",
"path": "<Keyboard>/j",
"interactions": "",
"processors": "",
"groups": "Keyboard&Mouse",
"action": "Cycle Target Item",
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "71ac6088-1e18-4810-86be-1179918dd4a2",

View file

@ -400,7 +400,27 @@ public class ActionGameManager : MonoBehaviour
var currentTargetIndex = Array.IndexOf(targets, CurrentEntity.Target.Value);
CurrentEntity.Target.Value = targets[(currentTargetIndex + targets.Length - 1) % targets.Length];
};
// Cut 2 (docs/fire-control-cut.md): cycles the aim point among the current target's revealed
// subsystems -- decides nothing itself, only calls the one writer (TrySelectTargetItem), same
// predicate (FireControl.IsRevealed) the AI path uses. No generated typed accessor exists for this
// action yet (it was hand-authored into Aetheria.inputactions rather than regenerated through the
// Unity Input Actions editor, unavailable here), so it is looked up by name instead of through
// Input.Player.
Input.asset.FindAction("Player/Cycle Target Item").performed += context =>
{
var target = CurrentEntity.Target.Value;
if (target == null) return;
var revealed = target.Equipment.Where(x => FireControl.IsRevealed(CurrentEntity, x)).ToArray();
if (revealed.Length == 0)
{
CurrentEntity.TrySelectTargetItem(null);
return;
}
var currentItemIndex = Array.IndexOf(revealed, CurrentEntity.ResolvedTargetItem);
CurrentEntity.TrySelectTargetItem(revealed[(currentItemIndex + 1) % revealed.Length]);
};
#endregion

View file

@ -33,6 +33,25 @@ public class CombatState : BaseState
var toTarget = target.Position - _agent.Ship.Position;
var targetDistance = length(toTarget);
// Cut 2 (docs/fire-control-cut.md): aim at whichever revealed weapon on the target hits hardest at
// this range, or clear the aim point when nothing qualifies -- the same predicate
// (FireControl.IsRevealed) and the same writer (TrySelectTargetItem) the player path uses.
EquippedItem bestTargetItem = null;
var bestTargetDps = float.MinValue;
foreach (var targetItem in target.Equipment)
{
if (!(targetItem.Behaviors.FirstOrDefault(b => b is Weapon) is Weapon targetWeapon)) continue;
if (!FireControl.IsRevealed(_agent.Ship, targetItem)) continue;
var dps = targetWeapon.RangeDamagePerSecond(targetDistance);
if (dps > bestTargetDps)
{
bestTargetDps = dps;
bestTargetItem = targetItem;
}
}
_agent.Ship.TrySelectTargetItem(bestTargetItem);
for (var i = 0; i < _agent.Ship.WeaponGroups.Length; i++)
{
var group = _agent.Ship.WeaponGroups[i];

View file

@ -183,6 +183,9 @@ public interface IPowerConsumer
Union(36, typeof(ConstantWeaponData)),
Union(37, typeof(ChargedWeaponData)),
Union(38, typeof(AutoWeaponData)),
// Cut 2 (docs/fire-control-cut.md): 39 is the next free index against this list, not the 39 the
// superseded draft quoted -- checked directly here rather than trusted from that document.
Union(39, typeof(TargetingSystemData)),
JsonObject(MemberSerialization.OptIn)]
public abstract class BehaviorData
{

View file

@ -0,0 +1,77 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using MessagePack;
using Newtonsoft.Json;
// Cut 2 (docs/fire-control-cut.md): the required interior Tool gear that makes aimed fire possible at all
// (R2, Q4). An entity with no working targeting system is not merely worse -- FireControl falls back to
// GameplaySettings.UnaidedAccuracy and a Precision of 0, which is authored to make unaided fire a last
// resort (Q4: "really, really bad"). This behaviour carries no power machinery of its own: EnergyDraw and
// Heat, authored alongside it on the same item, already cover that, and it adds nothing new.
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class TargetingSystemData : BehaviorData
{
// The ceiling on hit probability (Cut 3's roll multiplies against this; nothing here computes a
// probability). A stat, not a constant, so lot quality, wear, heat and PowerSupply all reach it through
// EquippedItem.Evaluate -- a starved targeting system rolls worse rather than switching off (the
// brownout ruling, docs/stats-and-power-cut.md, applied here).
[Inspectable, JsonProperty("accuracy"), Key(1), RuntimeInspectable]
public PerformanceStat Accuracy = new PerformanceStat();
// The info level (see Entity.EntityInfoGathered) at which sensor state stops limiting hits. Below the
// system's own resolution, an otherwise-earned hit still degrades on account of thin sensor data;
// consumed by Cut 3's roll.
[Inspectable, JsonProperty("resolution"), Key(2), RuntimeInspectable]
public PerformanceStat Resolution = new PerformanceStat();
// The chance a hit lands on the item actually aimed at (Entity.TargetItem) rather than a random cell.
// Consumed by Cut 3's roll.
[Inspectable, JsonProperty("precision"), Key(3), RuntimeInspectable]
public PerformanceStat Precision = new PerformanceStat();
// How much target-side deviation from the predicted intercept this system forgives before a shot goes
// wide. Consumed by Cut 3's roll; unused until then.
[Inspectable, JsonProperty("tracking"), Key(4), RuntimeInspectable]
public PerformanceStat Tracking = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new TargetingSystem(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new TargetingSystem(this, item);
}
}
public class TargetingSystem : Behavior
{
private readonly TargetingSystemData _data;
public float Accuracy { get; private set; }
public float Resolution { get; private set; }
public float Precision { get; private set; }
public float Tracking { get; private set; }
public TargetingSystem(TargetingSystemData data, EquippedItem item) : base(data, item)
{
_data = data;
}
public TargetingSystem(TargetingSystemData data, ConsumableItemEffect item) : base(data, item)
{
_data = data;
}
public override bool Execute(float dt)
{
Accuracy = Evaluate(_data.Accuracy);
Resolution = Evaluate(_data.Resolution);
Precision = Evaluate(_data.Precision);
Tracking = Evaluate(_data.Tracking);
return true;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e72dd6e15fead417f201fdc92c1fd259
timeCreated: 1758283200

View file

@ -45,6 +45,13 @@ public abstract class Entity
public List<Entity> Children = new List<Entity>();
public ReactiveProperty<Entity> Target = new ReactiveProperty<Entity>((Entity)null);
// Cut 2 (docs/fire-control-cut.md): the stored aim-point slot. Written only by TrySelectTargetItem
// below, and nulled whenever Target changes (subscribed in Activate). Do not read this field directly
// outside Entity -- read ResolvedTargetItem, which re-validates on every call, so decay (or the item
// leaving the target) drops the aim point the moment it is no longer earned, with no loop that has to
// notice and clear it.
public ReactiveProperty<EquippedItem> TargetItem = new ReactiveProperty<EquippedItem>((EquippedItem)null);
public float3 LookDirection;
public string Name;
@ -273,11 +280,42 @@ public abstract class Entity
foreach(var subscription in _watchedEntitySubscriptions[disappearingEntity.Value]) subscription.Dispose();
_watchedEntitySubscriptions.Remove(disappearingEntity.Value);
}));
// Cut 2 (docs/fire-control-cut.md): a Target change nulls the aim point. Fires immediately on
// subscribe with whatever Target already holds, which is harmless -- TargetItem starts null anyway.
_subscriptions.Add(Target.Subscribe(_ => TargetItem.Value = null));
if(WeaponGroups.All(wg=>!wg.items.Any()))
GenerateWeaponGroups();
}
// Cut 2 (docs/fire-control-cut.md): the only writer of TargetItem. Accepts null (clearing the aim
// point) or an item belonging to the current Target that FireControl.IsRevealed resolves true for this
// entity as observer. Returns whether the write took effect; a rejected non-null selection leaves
// TargetItem unchanged.
public bool TrySelectTargetItem(EquippedItem item)
{
if (item == null)
{
TargetItem.Value = null;
return true;
}
if (Target.Value == null || item.Entity != Target.Value || !FireControl.IsRevealed(this, item))
return false;
TargetItem.Value = item;
return true;
}
// The read path for TargetItem (see the field's own comment): null once the aimed item is no longer
// revealed to this entity, or no longer belongs to the current Target, even though nothing wrote
// TargetItem.Value at the moment that became true. Re-checked on every call; never cached.
public EquippedItem ResolvedTargetItem =>
TargetItem.Value != null && Target.Value == TargetItem.Value.Entity && FireControl.IsRevealed(this, TargetItem.Value)
? TargetItem.Value
: null;
// Another entity's stance toward THIS one, as far as this entity can perceive it: unknown (null)
// until this entity detects them, mirroring the existing detection model (VisibleEntities, driven
// by EntityInfoGathered crossing TargetDetectionInfoThreshold). Detected but not yet hostility-rated

View file

@ -2,13 +2,16 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Linq;
using CultMath;
using static CultMath.math;
// Cut 1 (docs/fire-control-cut.md): geometry only. Whether a weapon bears on a point is decided here and
// Cut 1 (docs/fire-control-cut.md): geometry -- whether a weapon bears on a point is decided here and
// nowhere else -- no prefab, transform, ArticulationPoint or renderer may influence it (R6, R7). Mount
// direction and arc are both derived per read from catalog data and the item's authored rotation; neither
// is ever stored on the entity.
// Cut 2 adds the reveal rule (R5) and the resolved targeting-system stats an entity fires with, both
// likewise derived on every read and never cached.
public static class FireControl
{
// The planar unit vector a hardpoint's weapon points along, derived solely from the item's authored
@ -40,4 +43,61 @@ public static class FireControl
var planarTarget = normalize(float3(toTarget.x, 0, toTarget.z));
return dot(MountDirection(weapon), planarTarget) >= cos(radians(arc / 2f));
}
// Cut 2, R5: whether `observer` has resolved `item` (which must belong to some entity in the zone) well
// enough to aim at it. Derived fresh from EntityInfoGathered on every call -- nothing caches a reveal
// result, so decay drops it the moment info falls back below tier, with no clearing loop anywhere.
//
// Ranking: the target's own non-hull equipment, hardpoint-mounted gear first (the big obvious things),
// then by size descending, ties broken by equipment order (OrderByDescending is a stable sort, so this
// needs no explicit tie-break key). Item i of N reveals once info crosses
// lerp(TargetArmorInfoThreshold, TargetGearInfoThreshold, i / max(1, N - 1)) -- the first item to reveal
// does so at the armor tier, the last at the gear tier.
public static bool IsRevealed(Entity observer, EquippedItem item)
{
var target = item.Entity;
var ranked = target.Equipment
.Where(e => e.Data.HardpointType != HardpointType.Hull)
.OrderByDescending(e => e.Data.HardpointType != HardpointType.Tool)
.ThenByDescending(e => e.Data.Shape.Coordinates.Length)
.ToList();
var index = ranked.IndexOf(item);
if (index < 0) return false; // the hull itself, or an item that is no longer on this target
var settings = observer.ItemManager.GameplaySettings;
var info = observer.EntityInfoGathered.TryGetValue(target, out var gathered) ? gathered : 0f;
var tier = lerp(settings.TargetArmorInfoThreshold, settings.TargetGearInfoThreshold,
(float) index / max(1, ranked.Count - 1));
return info >= tier;
}
// Cut 2, Q4: the stats an entity actually fires with. A working targeting system (equipped, online --
// not destroyed, not shut down) supplies its own resolved stats; anything else falls back to the
// authored unaided figures, which make aiming without one a last resort rather than an alternative.
// Cut 3's roll is the only planned reader.
public static float Accuracy(Entity entity)
{
var system = entity.GetBehavior<TargetingSystem>();
return system != null && system.Item.Active.Value
? system.Accuracy
: entity.ItemManager.GameplaySettings.UnaidedAccuracy;
}
public static float Resolution(Entity entity)
{
var system = entity.GetBehavior<TargetingSystem>();
return system != null && system.Item.Active.Value ? system.Resolution : 1f;
}
public static float Precision(Entity entity)
{
var system = entity.GetBehavior<TargetingSystem>();
return system != null && system.Item.Active.Value ? system.Precision : 0f;
}
public static float Tracking(Entity entity)
{
var system = entity.GetBehavior<TargetingSystem>();
return system != null && system.Item.Active.Value ? system.Tracking : 0f;
}
}

View file

@ -258,6 +258,26 @@ public class LoadoutGenerator
capacitor.Rotation = capacitorRotation;
if (!entity.TryEquip(capacitor, capacitorPosition))
throw new InvalidLoadoutException("Failed to equip selected capacitor!");
// Cut 2 (docs/fire-control-cut.md, Q4): required equipment for anything that can fire -- unaided
// fire is a last resort, not an alternative loadout choice. EquipHardpoints runs before FillInterior
// (OutfitEntity), so entity.Weapons is already populated here. Zenith and anything else with no
// weapon hardpoints gets none.
if (entity.Weapons.Any())
{
emptyShape = entity.UnoccupiedSpace;
var (targetingProduct, targetingData) = RandomProduct<GearData>(2, item =>
item.Behaviors.Any(b => b is TargetingSystemData) &&
item.Shape.FitsWithin(emptyShape, out _, out _), required: true);
if (targetingData == null) throw new InvalidLoadoutException("No compatible targeting system found for entity!");
targetingData.Shape.FitsWithin(emptyShape, out var targetingRotation, out var targetingPosition);
var targetingSystem = ItemManager.CreateInstance(targetingProduct) as EquippableItem;
targetingSystem.Rotation = targetingRotation;
if (!entity.TryEquip(targetingSystem, targetingPosition))
throw new InvalidLoadoutException("Failed to equip selected targeting system!");
}
}
}

View file

@ -213,6 +213,14 @@ public class GameplaySettings
public float TargetGearInfoThreshold;
public float ConvergenceMinimumDistance;
public float FiringArc = 120;
// Cut 2 (docs/fire-control-cut.md, Q4): what an entity with no working targeting system fires with --
// the ceiling FireControl.Accuracy falls back to (Resolution 1, Precision 0 alongside it). Authored low
// on purpose ("really, really bad," operator 2026-09-19): .05 against the two catalog designs' own
// Accuracy ranges (the authoring spec this cut produces proposes .45-.6 for the 1-cell design and
// .65-.85 for the 2-cell one) leaves unaided fire capable of hitting something close, slow and
// unaware, and little else. One authored setting, easy to find and turn -- the operator rules the real
// figure in play.
public float UnaidedAccuracy = .05f;
public float AgentRangeExponent = .25f;
public float AgentForwardLerp = .5f;
public float AgentMaxForwardDistance = 50;

View file

@ -106,8 +106,11 @@ public class SchematicDisplay : MonoBehaviour
CargoTemperatureLabel.text = "N/A";
}
// Cut 2 (docs/fire-control-cut.md): an enemy schematic shows only what `player` has actually
// resolved (FireControl.IsRevealed) -- the same predicate the selection writer and the AI use. The
// player's own schematic is unfiltered; there is nothing to reveal about your own ship.
_schematicItems = entity.Equipment
.Where(x => x.Behaviors.Any(b => b.Data is WeaponData))
.Where(x => x.Behaviors.Any(b => b.Data is WeaponData) && (!_enemy || FireControl.IsRevealed(player, x)))
.Select(x => new SchematicDisplayItem
{
Item = x,
@ -201,6 +204,13 @@ public class SchematicDisplay : MonoBehaviour
// DistanceLabel.text = $"{(int)length(_entity.Position - _player.Position)}";
// }
// Cut 2 (docs/fire-control-cut.md): marks whichever row is the player's current aim point.
// Re-checked every frame (not just on ShowShip) because ResolvedTargetItem can drop on its own
// as info decays, with no event to hook.
if (_enemy && _schematicItems != null)
foreach (var x in _schematicItems)
x.ListElement.SetSelected(x.Item == _player.ResolvedTargetItem);
if(VisibilityLabel)
VisibilityLabel.text = ((int)_entity.Visibility).ToString();

View file

@ -15,8 +15,18 @@ public class SchematicListElement : MonoBehaviour
public RectTransform CooldownFill;
public RectTransform HeatFill;
// Cut 2 (docs/fire-control-cut.md): marks this row as the current aim point (Entity.ResolvedTargetItem)
// on an enemy schematic. Unassigned in a prefab that has not been wired up in the Unity editor yet
// (unavailable in this pass) -- SetSelected below is a no-op until then, not a null reference.
public GameObject SelectedIndicator;
private List<Prototype> _iconInstances = new List<Prototype>();
public void SetSelected(bool selected)
{
if (SelectedIndicator != null) SelectedIndicator.SetActive(selected);
}
public void ShowWeapon(WeaponItemData weapon)
{
foreach(var prototype in _iconInstances) prototype.ReturnToPool();

View file

@ -39,8 +39,13 @@ public sealed class LoadoutTests : IDisposable
var cargo = cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = new Shape(), Price = 5 });
var gun = cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Behaviors = { new InstantWeaponData() } });
cache.Upsert(new GearData { Name = "Orphan", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1 });
// Cut 2 (docs/fire-control-cut.md, Q4): required equipment for any entity with a weapon
// (LoadoutGenerator.FillInterior). "Gun" carries a weapon behaviour and shares this catalog's one
// Sensors hardpoint type with "Lamp"/"Orphan", so any generated loadout that happens to draw Gun
// needs a targeting-system product available or FillInterior throws.
var targeting = cache.Upsert(new GearData { Name = "Scope", Hardpoint = HardpointType.Tool, Shape = new Shape(), Price = 1, Behaviors = { new TargetingSystemData() } });
foreach (var (name, design) in new[] { ("Skiff by Maker", hull.Key), ("Lamp by Maker", gear.Key), ("Crate by Maker", cargo.Key), ("Gun by Maker", gun.Key) })
foreach (var (name, design) in new[] { ("Skiff by Maker", hull.Key), ("Lamp by Maker", gear.Key), ("Crate by Maker", cargo.Key), ("Gun by Maker", gun.Key), ("Scope by Maker", targeting.Key) })
cache.Upsert(new FactionProductData { Name = name, Design = new CultRecordRef<CraftedItemData>(design), Manufacturer = maker });
cache.FlushAsync().Wait();
}

View file

@ -0,0 +1,404 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using Xunit;
using static CultMath.math;
using float3 = CultMath.float3;
using Random = CultMath.Random;
// Cut 2 (docs/fire-control-cut.md): pins the targeting subsystem, the reveal rule between the two info
// thresholds, the selection slot/predicate, and the required-equipment ruling (Q4). Builds its own
// hull/catalog fixtures, the same style FireControlTests uses for Cut 1, rather than reusing that file's
// or LoadoutTests' private helpers.
public sealed class TargetingSystemTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-targeting-" + Guid.NewGuid().ToString("N"));
private string Catalog => Path.Combine(_root, "Aetheria.cc");
public TargetingSystemTests() => Directory.CreateDirectory(_root);
private CultCache _openCache;
public void Dispose()
{
_openCache?.Dispose();
Directory.Delete(_root, true);
}
private static GameplaySettings TestSettings() => new GameplaySettings
{
DefaultEntitySettings = new EntitySettings(),
Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } },
QualityPriceModifier = new ExponentialLerp(),
TargetArmorInfoThreshold = .3f,
TargetGearInfoThreshold = .9f,
UnaidedAccuracy = .1f,
FiringArc = 120
};
private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v };
// Min=0 (not Min=Max): a PowerSupply term can only be observed to degrade something with room to move
// between floor and authored ceiling (BrownoutTests' own convention).
private static PerformanceStat Curved(float max, float exponent) =>
new PerformanceStat { Min = 0, Max = max, Terms = { new StatTerm { Source = StatSource.PowerSupply, Exponent = exponent } } };
// A 6x4 hull with one Sensors hardpoint at (0,0) (hardpoint-mounted weapon) and interior room for two
// more Tool items, one 2-cell and one 1-cell. Non-hull equipment ends up authored in this order --
// hardpoint weapon, wide interior item, narrow interior item -- but it is FireControl.IsRevealed's own
// ranking, not authoring order, that RevealOrder actually pins.
// `targetingData`, when given, authors a fourth non-hull item (a Tool gear carrying that behaviour) in
// the same catalog-build pass, so a test that needs a targeting system never has to reopen the catalog
// file after the live, already-open ItemManager exists (CultCache is single-writer).
private (ItemManager items, Ship target, EquippedItem weapon, EquippedItem wideItem, EquippedItem narrowItem, EquippedItem targetingItem)
BuildTarget(GameplaySettings settings, TargetingSystemData targetingData = null)
{
var hullShape = new Shape(6, 4);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
var hullData = new HullData
{
Name = "TestHull", HullType = HullType.Ship, Shape = hullShape, Durability = 1, Mass = 1000,
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } }
};
using (var buildCache = AetheriaStores.Open(Catalog, catalogWritable: true))
{
buildCache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
buildCache.Upsert(hullData);
buildCache.Upsert(new GearData
{
Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
Behaviors = { new InstantWeaponData() }
});
var wideShape = new Shape(2, 1);
wideShape[new int2(0, 0)] = true;
wideShape[new int2(1, 0)] = true;
buildCache.Upsert(new GearData
{
Name = "Wide", Hardpoint = HardpointType.Tool, Shape = wideShape, Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000
});
buildCache.Upsert(new GearData
{
Name = "Narrow", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000
});
if (targetingData != null)
buildCache.Upsert(new GearData
{
Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
Behaviors = { targetingData }
});
buildCache.FlushAsync().Wait();
}
_openCache = AetheriaStores.Open(Catalog, catalogWritable: true);
var ledger = new ProvenanceLedger();
ledger.Lots[1] = new Lot { Origin = new Attributed(), Quality = 1 }; // hull
ledger.Lots[2] = new Lot { Origin = new Attributed(), Quality = 1 }; // gun
ledger.Lots[3] = new Lot { Origin = new Attributed(), Quality = 1 }; // wide
ledger.Lots[4] = new Lot { Origin = new Attributed(), Quality = 1 }; // narrow
ledger.Lots[5] = new Lot { Origin = new Attributed(), Quality = 1 }; // targeting (unused unless authored above)
var items = new ItemManager(_openCache, ledger, settings, _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var hullRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("TestHull"));
var hull = new EquippableItem { Data = hullRef, Durability = 1, Lot = 1 };
var target = new Ship(items, zone, hull, new EntitySettings());
var gunRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<GearData>("Gun"));
var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 };
Assert.True(target.TryEquip(gun, new int2(0, 0)));
var weapon = target.Equipment.Single(e => e.EquippableItem == gun);
var wideRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<GearData>("Wide"));
var wide = new EquippableItem { Data = wideRef, Durability = 1, Lot = 3 };
Assert.True(target.TryFindSpace(wide, out var widePos));
Assert.True(target.TryEquip(wide, widePos));
var wideItem = target.Equipment.Single(e => e.EquippableItem == wide);
var narrowRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<GearData>("Narrow"));
var narrow = new EquippableItem { Data = narrowRef, Durability = 1, Lot = 4 };
Assert.True(target.TryFindSpace(narrow, out var narrowPos));
Assert.True(target.TryEquip(narrow, narrowPos));
var narrowItem = target.Equipment.Single(e => e.EquippableItem == narrow);
EquippedItem targetingItem = null;
if (targetingData != null)
{
var targetingRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<GearData>("Targeting"));
var targeting = new EquippableItem { Data = targetingRef, Durability = 1, Lot = 5 };
Assert.True(target.TryFindSpace(targeting, out var targetingPos));
Assert.True(target.TryEquip(targeting, targetingPos));
targetingItem = target.Equipment.Single(e => e.EquippableItem == targeting);
}
zone.Entities.Add(target);
target.Activate();
return (items, target, weapon, wideItem, narrowItem, targetingItem);
}
// A bare-hull observer sharing the target's zone, with no equipment of its own -- only its
// EntityInfoGathered dictionary and Target/TrySelectTargetItem matter to these tests.
private Ship BuildObserver(ItemManager items, Zone zone)
{
var hullRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("TestHull"));
var hull = new EquippableItem { Data = hullRef, Durability = 1, Lot = 1 };
var observer = new Ship(items, zone, hull, new EntitySettings());
zone.Entities.Add(observer);
observer.Activate();
return observer;
}
// R5 / the selection predicate: TrySelectTargetItem accepts only a revealed item of the current target,
// a Target change nulls the aim point, and decay drops it on read with no loop clearing it.
// Mutation: IsRevealed returns true unconditionally; the Target-change subscription is removed; or
// ResolvedTargetItem returns TargetItem.Value without re-checking.
[Fact]
public void SelectionNeedsReveal()
{
var (items, target, weapon, _, _, _) = BuildTarget(TestSettings());
var observer = BuildObserver(items, target.Zone);
observer.Target.Value = target;
observer.EntityInfoGathered[target] = .29f; // below the single item's own tier (Armor, N==1)
Assert.False(observer.TrySelectTargetItem(weapon));
Assert.Null(observer.TargetItem.Value);
observer.EntityInfoGathered[target] = .3f; // at tier: revealed
Assert.True(observer.TrySelectTargetItem(weapon));
Assert.Same(weapon, observer.TargetItem.Value);
Assert.Same(weapon, observer.ResolvedTargetItem);
// A Target change nulls the aim point.
observer.Target.Value = null;
Assert.Null(observer.TargetItem.Value);
// Decay: re-select, then let info fall back below tier without touching TargetItem.Value at all --
// the raw field still holds the item (no loop cleared it), but the read accessor drops it.
observer.Target.Value = target;
Assert.True(observer.TrySelectTargetItem(weapon));
observer.EntityInfoGathered[target] = .1f;
Assert.Same(weapon, observer.TargetItem.Value);
Assert.Null(observer.ResolvedTargetItem);
}
// The ranking: hardpoint-mounted gear before interior Tool gear, larger before smaller within a group.
// Mutation: drop the ordering (e.g. rank by equipment order alone).
[Fact]
public void RevealOrder()
{
var (items, target, weapon, wideItem, narrowItem, _) = BuildTarget(TestSettings());
var observer = BuildObserver(items, target.Zone);
observer.EntityInfoGathered[target] = .35f; // above Armor (.3, index 0), below the mid tier (.6, index 1)
Assert.True(FireControl.IsRevealed(observer, weapon));
Assert.False(FireControl.IsRevealed(observer, wideItem));
Assert.False(FireControl.IsRevealed(observer, narrowItem));
observer.EntityInfoGathered[target] = .65f; // above the mid tier, below Gear (.9, index 2)
Assert.True(FireControl.IsRevealed(observer, weapon));
Assert.True(FireControl.IsRevealed(observer, wideItem));
Assert.False(FireControl.IsRevealed(observer, narrowItem));
observer.EntityInfoGathered[target] = .95f; // above Gear: everything revealed
Assert.True(FireControl.IsRevealed(observer, weapon));
Assert.True(FireControl.IsRevealed(observer, wideItem));
Assert.True(FireControl.IsRevealed(observer, narrowItem));
}
// The tiers really are the two authored settings: the first item reveals exactly at
// TargetArmorInfoThreshold, the last exactly at TargetGearInfoThreshold. Mutation: swap the two
// settings, or use TargetDetectionInfoThreshold instead.
[Fact]
public void RevealSpansBothThresholds()
{
var settings = TestSettings();
var (items, target, weapon, wideItem, narrowItem, _) = BuildTarget(settings);
var observer = BuildObserver(items, target.Zone);
observer.EntityInfoGathered[target] = settings.TargetArmorInfoThreshold;
Assert.True(FireControl.IsRevealed(observer, weapon));
Assert.False(FireControl.IsRevealed(observer, wideItem));
Assert.False(FireControl.IsRevealed(observer, narrowItem));
observer.EntityInfoGathered[target] = settings.TargetGearInfoThreshold;
Assert.True(FireControl.IsRevealed(observer, weapon));
Assert.True(FireControl.IsRevealed(observer, wideItem));
Assert.True(FireControl.IsRevealed(observer, narrowItem));
}
// Q4: the subsystem is what supplies accuracy. No targeting system, a destroyed one, and a disabled one
// all resolve the authored unaided figures. Mutation: fall back to the (destroyed/offline) system's own
// stats instead of the unaided ones.
[Fact]
public void UnaidedFiresWorse()
{
var settings = TestSettings();
var targetingData = new TargetingSystemData
{
Accuracy = Constant(.8f), Resolution = Constant(.6f), Precision = Constant(.7f), Tracking = Constant(.5f)
};
var (items, target, _, _, _, targetingUnit) = BuildTarget(settings, targetingData);
var equippedTargeting = targetingUnit;
var system = equippedTargeting.Behaviors.OfType<TargetingSystem>().Single();
system.Execute(0f);
// No targeting system at all: a second, bare-hull ship in the same catalog/zone (one CultCache
// handle stays open per test -- BuildTarget is not called twice).
var bareShip = BuildObserver(items, target.Zone);
Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(bareShip), 4);
Assert.Equal(0f, FireControl.Precision(bareShip), 4);
Assert.Equal(1f, FireControl.Resolution(bareShip), 4);
// Bring it online to prove the fixture can actually supply its own stats...
equippedTargeting.UpdatePerformance();
Assert.True(equippedTargeting.Active.Value);
Assert.Equal(.8f, FireControl.Accuracy(target), 4);
Assert.Equal(.7f, FireControl.Precision(target), 4);
// ...then destroy it: durability gone, still falls back.
equippedTargeting.EquippableItem.Durability = 0f;
equippedTargeting.UpdatePerformance();
Assert.False(equippedTargeting.Active.Value);
Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(target), 4);
Assert.Equal(0f, FireControl.Precision(target), 4);
Assert.Equal(1f, FireControl.Resolution(target), 4);
// Repair it, then disable it directly instead: same fallback.
equippedTargeting.EquippableItem.Durability = 1f;
equippedTargeting.UpdatePerformance();
Assert.True(equippedTargeting.Active.Value);
equippedTargeting.Enabled.Value = false;
Assert.False(equippedTargeting.Active.Value);
Assert.Equal(settings.UnaidedAccuracy, FireControl.Accuracy(target), 4);
Assert.Equal(0f, FireControl.Precision(target), 4);
}
// The brownout ruling (docs/stats-and-power-cut.md) applies to Accuracy same as any other stat: a
// half-grant halves it (PowerSupply exponent 1), not a switch-off. Reactor + a real PowerBus tick, the
// same fixture shape BrownoutTests uses, because Item.PowerSupply's setter is internal to a different
// assembly here and can only be driven through a live grant.
[Fact]
public void StarvedTargetingRollsWorse()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
var hullShape = new Shape(5, 5);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10, Mass = 1000 });
cache.Upsert(new GearData
{
Name = "Reactor", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
Behaviors = { new ReactorData { Charge = Constant(0), Efficiency = Constant(1), OverloadEfficiency = Constant(1), ThrottlingFactor = Constant(2) } }
});
cache.Upsert(new GearData
{
Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
Behaviors =
{
new EnergyDrawData { EnergyDraw = Constant(100) },
new TargetingSystemData { Accuracy = Curved(1, 1), Resolution = Constant(1), Precision = Constant(1), Tracking = Constant(1) }
}
});
cache.FlushAsync().Wait();
EquippableItem Mint(ItemData design) => new EquippableItem
{
Data = cache.RefOf<ItemData>(design),
Durability = design is EquippableItemData equippable ? equippable.Durability : 0,
};
Ship BuildShip(float reactorCharge, out ItemManager items)
{
items = new ItemManager(cache, new ProvenanceLedger(), TestSettings(), _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var hullData = cache.GetByName<HullData>("Skiff");
var hull = Mint(hullData);
hull.Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(hullData), Origin = new Attributed(), Quality = .5f, Roles = new System.Collections.Generic.List<RoleFill>() });
var ship = new Ship(items, zone, hull, new EntitySettings());
var reactorData = cache.GetByName<GearData>("Reactor");
((ReactorData) reactorData.Behaviors[0]).Charge = Constant(reactorCharge);
var reactor = Mint(reactorData);
reactor.Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(reactorData), Origin = new Attributed(), Quality = .5f, Roles = new System.Collections.Generic.List<RoleFill>() });
Assert.True(ship.TryEquip(reactor));
var targetingData = cache.GetByName<GearData>("Targeting");
var targeting = Mint(targetingData);
targeting.Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(targetingData), Origin = new Attributed(), Quality = .5f, Roles = new System.Collections.Generic.List<RoleFill>() });
Assert.True(ship.TryEquip(targeting));
zone.Entities.Add(ship);
ship.LookDirection = float3(0, 0, 1);
ship.Activate();
return ship;
}
float ResolveAccuracy(float reactorCharge)
{
var ship = BuildShip(reactorCharge, out _);
ship.Update(1f); // one tick: PowerBus.Step grants, then Execute resolves Accuracy against it
return FireControl.Accuracy(ship);
}
var full = ResolveAccuracy(1000); // demand 100, generation far exceeds it -> ratio 1
var half = ResolveAccuracy(50); // demand 100, generation 50 -> ratio .5
Assert.Equal(1f, full, 3);
Assert.Equal(.5f, half, 3);
}
// Q4: required equipment for anything that can fire. Across several seeds, every generated loadout with
// a weapon also carries a targeting system. Mutation: drop `required: true` on the targeting-system
// RandomProduct call in LoadoutGenerator.FillInterior.
[Fact]
public void EveryArmedLoadoutGetsATargetingSystem()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
var maker = cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" });
var hullShape = new Shape(5, 5);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
var hull = cache.Upsert(new HullData
{
Name = "Armed", HullType = HullType.Ship, Shape = hullShape, Price = 100,
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } }
});
var gun = cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Behaviors = { new InstantWeaponData() } });
var cargo = cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = new Shape(), Price = 5 });
var capacitor = cache.Upsert(new GearData { Name = "Cap", Hardpoint = HardpointType.Tool, Shape = new Shape(), Price = 1, Behaviors = { new CapacitorData() } });
var targeting = cache.Upsert(new GearData { Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Price = 1, Behaviors = { new TargetingSystemData() } });
foreach (var (name, design) in new[]
{
("Armed by Maker", hull.Key), ("Gun by Maker", gun.Key), ("Crate by Maker", cargo.Key),
("Cap by Maker", capacitor.Key), ("Targeting by Maker", targeting.Key)
})
cache.Upsert(new FactionProductData { Name = name, Design = new CultRecordRef<CraftedItemData>(design), Manufacturer = maker });
cache.FlushAsync().Wait();
for (var seed = 1; seed <= 10; seed++)
{
var random = new Random((uint) seed);
var items = new ItemManager(cache, new ProvenanceLedger(), TestSettings(), _ => { });
var generator = new LoadoutGenerator(ref random, items, null, null, null, .5f);
var pack = generator.GenerateShipLoadout(candidate => candidate.Name == "Armed");
Assert.NotNull(pack);
Assert.Contains(pack.Equipment, e => (cache.Get(e.item.Data) as GearData)?.Behaviors.Any(b => b is TargetingSystemData) ?? false);
}
}
}