From 39ad4bfc80bfc050944db1e82bb5a8dacb35c83d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 18:34:04 +0200 Subject: [PATCH 1/2] Fire control Cut 6b: a shot's dice belong to the shot, and airburst resolves in the simulation 6.1 (Soul finding 6): Commit builds a local CultMath.Random from (Zone.CombatSeed, shot.ShotId) instead of reading and writing the shared ItemManager.Random stream. Zone exposes CombatSeed (the same expression that already seeds its own _random), so a shot's outcome is a pure function of zone identity and shot id -- immune to whatever else drew from the shared stream in between. 6.2 (Soul finding 5): airburst is wired into the simulation instead of back into Projectile.cs. PendingShot gains BurstPosition/BurstRadius, frozen at Fire time from PredictedIntercept and the weapon's authored WeaponItemData.AirburstRange when WeaponModifiers carries Airburst. FireControl.Step resolves such a shot via Splash instead of Apply, never both. Projectile.cs/ProjectileManager.cs drop the dead AirburstDistance/AirburstRange fields and write-back. Tests: FireControlCut6Tests.cs pins both rules (208 baseline + 5 new, all green). Co-Authored-By: Claude Sonnet 5 --- Assets/Scripts/Gameplay/Weapons/Projectile.cs | 9 +- .../Gameplay/Weapons/ProjectileManager.cs | 3 - Assets/Scripts/ServerShared/FireControl.cs | 32 +- Assets/Scripts/ServerShared/ItemData.cs | 7 + Assets/Scripts/ServerShared/Zone.cs | 9 +- .../FireControlCut6Tests.cs | 310 ++++++++++++++++++ 6 files changed, 358 insertions(+), 12 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs diff --git a/Assets/Scripts/Gameplay/Weapons/Projectile.cs b/Assets/Scripts/Gameplay/Weapons/Projectile.cs index 8f3683772..b76fa6b0f 100644 --- a/Assets/Scripts/Gameplay/Weapons/Projectile.cs +++ b/Assets/Scripts/Gameplay/Weapons/Projectile.cs @@ -4,8 +4,10 @@ using static CultMath.math; // Cut 3 (docs/fire-control-cut.md): the raycast, shield branch and SendHit are deleted -- FireControl already // decided this shot's fate before this object was ever spawned (R8). What is left is pure flight-path -// presentation: fly, and disappear at Range or ShotId's resolution, whichever comes first. Airburst -// (AirburstDistance/AirburstRange) is Cut 4's -- untouched here. +// presentation: fly, and disappear at Range or ShotId's resolution, whichever comes first. +// Cut 6b, 6.2: airburst resolves in the simulation now (FireControl.Step calls Splash instead of Apply at +// arrival) -- a MonoBehaviour calling Splash would be exactly the authority Cut 3 spent itself deleting, so +// AirburstDistance/AirburstRange are gone. This object's job stays fly-and-disappear. public class Projectile : MonoBehaviour { public TrailRenderer Trail; @@ -13,9 +15,6 @@ public class Projectile : MonoBehaviour public float Drag = .1f; public Prototype HitEffect; - public float AirburstDistance; - public float AirburstRange; - private bool _alive; // Cut 3: FireControl.Fire's ShotId -- this projectile's handle onto Zone.ShotCommitted/ShotResolved. diff --git a/Assets/Scripts/Gameplay/Weapons/ProjectileManager.cs b/Assets/Scripts/Gameplay/Weapons/ProjectileManager.cs index 3ef9edc64..c9fc2e13f 100644 --- a/Assets/Scripts/Gameplay/Weapons/ProjectileManager.cs +++ b/Assets/Scripts/Gameplay/Weapons/ProjectileManager.cs @@ -1,8 +1,6 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; -using CultMath; -using static CultMath.math; using Random = UnityEngine.Random; public class ProjectileManager : InstantWeaponEffectManager @@ -29,7 +27,6 @@ public class ProjectileManager : InstantWeaponEffectManager p.Velocity += new Vector3(source.Entity.Velocity.x, 0, source.Entity.Velocity.y); p.Range = weapon.Range; p.Zone = source.Entity.Zone; - p.AirburstDistance = target != null ? length(source.Entity.Position - target.Entity.Position) : (weapon.Range * .75f); p.Trail.Clear(); } } diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 65a20a88e..6bb65be55 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -195,6 +195,15 @@ public static class FireControl } var commitHorizon = source.ItemManager.GameplaySettings.CommitHorizon; + + // Cut 6b, 6.2 (Soul finding 5): airburst is a property of the weapon, resolved and frozen here like + // every other payload field -- never decided later by a Unity projectile. A weapon without the + // Airburst flag freezes a zero radius, which Step below reads as "resolve this shot with Apply." + var weaponItemData = item.Data as WeaponItemData; + var isAirburst = weaponItemData != null && weaponItemData.WeaponModifiers.HasFlag(WeaponModifiers.Airburst); + var burstPosition = isAirburst && target != null ? PredictedIntercept(weapon, source, target) : targetPosition; + var burstRadius = isAirburst ? weaponItemData.AirburstRange : 0f; + var shot = new PendingShot { ShotId = zone.NextShotId(), @@ -214,6 +223,8 @@ public static class FireControl FireTargetVelocity = targetVelocity, ArrivalTime = now + flightTime, CommitTime = now + max(0f, flightTime - commitHorizon), + BurstPosition = burstPosition, + BurstRadius = burstRadius, Committed = false }; @@ -258,7 +269,11 @@ public static class FireControl if (shot.Committed && now >= shot.ArrivalTime) { - Apply(shot); + // Cut 6b, 6.2: an airburst shot (frozen BurstRadius > 0) resolves as an area effect instead of + // a discrete hit -- Splash instead of Apply, never both, which is exactly the double- + // application Soul was told to hunt for. + if (shot.BurstRadius > 0f) Splash(zone, shot.BurstPosition, shot.BurstRadius, shot.Damage, shot.DamageType); + else Apply(shot); zone.ShotResolved.OnNext(shot.Outcome); shots.RemoveAt(i); } @@ -272,7 +287,13 @@ public static class FireControl // sequence is exactly as if the shot had never queued. private static ShotOutcome Commit(Zone zone, PendingShot shot, float now) { - var random = shot.Source.ItemManager.Random; + // Cut 6b, 6.1 (Soul finding 6): a shot's dice belong to the shot, not to whatever else happened to + // draw from ItemManager.Random first. A pure function of (zone identity, shot id) -- the `| 1u` guards + // the degenerate zero seed -- so two runs of the same fight from the same galaxy seed roll identically + // no matter what the UI drew from the shared stream in between. This generator is local and dies with + // the call: nothing outside Commit may seed or advance a combat draw, and Commit may not read or write + // a shared stream. + var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u); var p = shot.PBase; if (p > 0f && shot.Target != null) { @@ -312,7 +333,6 @@ public static class FireControl else if (shieldActive) shieldBroken = true; } - shot.Source.ItemManager.Random = random; return MakeOutcome(shot, hit, shielded, shieldBroken, cell, aimed, now); } @@ -436,6 +456,12 @@ public struct PendingShot public float Tracking; public float Precision; + // Cut 6b, 6.2: the airburst payload, frozen at fire alongside everything else above. BurstRadius is zero + // for a weapon without the Airburst flag (WeaponModifiers, Enums.cs) -- Step reads that zero as "resolve + // with Apply," not a separate bool. + public float3 BurstPosition; + public float BurstRadius; + public float3 FireTargetPosition; public float3 FireTargetVelocity; public float FireTime; diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index 5e82ea6d7..384edf728 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -489,6 +489,13 @@ public class WeaponItemData : GearData [Inspectable, JsonProperty("modifiers"), Key(28)] public WeaponModifiers WeaponModifiers; + + // Cut 6b (docs/fire-control-cut.md, 6.2): the authored blast radius an Airburst-flagged weapon's shot + // splashes with at arrival, frozen into PendingShot.BurstRadius at fire. Zero (and unread) for a weapon + // without the Airburst flag. No authored value exists yet -- the flag is wired and unexercised until Cut + // 6a or a later authoring pass sets it. + [Inspectable, JsonProperty("airburstRange"), Key(29)] + public float AirburstRange; } [CultDocument("aetheria.hulldata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index c7cae537f..5011a3f94 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -53,6 +53,12 @@ public class Zone public GalaxyZone GalaxyZone { get; } public Galaxy Galaxy { get; } + // Cut 6b (docs/fire-control-cut.md, 6.1, Soul finding 6): one zone, one stable identity -- a galaxy seed + // reproduces it, and nothing else in the zone (an NPC joining, a shop opening, a wormhole exit) can + // perturb it. FireControl.Commit builds its own local generator from this and the shot's own id instead + // of touching a shared stream. + public uint CombatSeed { get; } + public Zone(ItemManager itemManager, PlanetSettings settings, ZonePack pack, GalaxyZone galaxyZone, Galaxy galaxy) { _time = pack.Time; @@ -61,7 +67,8 @@ public class Zone Pack = pack; _itemManager = itemManager; Settings = settings; - _random = new Random(galaxyZone?.Name.StableHash() ?? 1337u); + CombatSeed = galaxyZone?.Name.StableHash() ?? 1337u; + _random = new Random(CombatSeed); var cache = itemManager.ItemData; // Cut 5, 5.6 (docs/fire-control-cut.md, Soul finding 7; operator ruling Q3): death removes the ship, diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs new file mode 100644 index 000000000..1054c25a3 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs @@ -0,0 +1,310 @@ +/* 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.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using UniRx; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; +using int2 = CultMath.int2; +using Random = CultMath.Random; + +// Cut 6b (docs/fire-control-cut.md, "the dice stop being shared, and the flak cannon works again"): pins 6.1 +// (a shot's dice are a pure function of zone identity and shot id, not a shared stream) and 6.2 (airburst +// resolves in the simulation, via Splash instead of Apply, never both). Builds its own fixtures, the same +// convention every earlier cut's test file establishes. +public sealed class FireControlCut6Tests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolcut6-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public FireControlCut6Tests() => Directory.CreateDirectory(_root); + + private readonly List _openCaches = new List(); + + public void Dispose() + { + foreach (var c in _openCaches) c.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(), + TargetDetectionInfoThreshold = .1f, + TargetArmorInfoThreshold = .2f, + TargetGearInfoThreshold = .8f, + FiringArc = 170, + CommitHorizon = .5f, + SchematicCellSize = 1f, + UnaidedAccuracy = .05f, + UnaidedTracking = 10f, + AgentMinHitProbability = 0f, + BeamResolveInterval = .1f + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + private static Shape SolidShape(int w, int h) + { + var shape = new Shape(w, h); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // ---- A discrete-weapon shooter/target engagement, the same shape FireControlCut5Tests.Build uses. Every + // engagement shares the fixed GalaxyZone name "Test", so every Zone built from this fixture shares one + // CombatSeed (R1's stable identity) -- exactly the substrate 6.1's determinism claim depends on. ---- + + private sealed class Engagement + { + public ItemManager Items; + public Zone Zone; + public Ship Shooter; + public Ship Target; + public EquippedItem WeaponItem; + public InstantWeapon Weapon; + } + + private Engagement Build( + GameplaySettings settings, + float damage = 10, float range = 1000, float velocity = 0, float spread = 0, + float accuracy = 1, float resolution = 1, float tracking = 100000, + float targetRange = 100, bool airburst = false, float airburstRange = 0) + { + var hullShape = SolidShape(5, 5); + var hullData = new HullData + { + Name = "Hull", HullType = HullType.Ship, Shape = hullShape, Durability = 100000, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }; + + var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); + _openCaches.Add(cache); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(hullData); + // Cut 6b, 6.2: a real WeaponItemData (not the bare GearData earlier cuts' fixtures use) -- it is the + // one catalog type carrying WeaponModifiers (the Airburst flag) and, since this cut, AirburstRange. + cache.Upsert(new WeaponItemData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + WeaponModifiers = airburst ? WeaponModifiers.Airburst : WeaponModifiers.None, + AirburstRange = airburstRange, + Behaviors = { new InstantWeaponData + { + Damage = Constant(damage), Range = Constant(range), MinRange = Constant(0), + Velocity = Constant(velocity), Spread = Constant(spread), DamageSpread = Constant(0), + Penetration = Constant(0), Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1000), + DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } } + } } + }); + cache.Upsert(new GearData + { + Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new TargetingSystemData + { + Accuracy = Constant(accuracy), Resolution = Constant(resolution), Precision = Constant(0), Tracking = Constant(tracking) + } } + }); + cache.FlushAsync().Wait(); + + var ledger = new ProvenanceLedger(); + ledger.Lots[1] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[2] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[3] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[4] = new Lot { Origin = new Attributed(), Quality = 1 }; + ledger.Lots[5] = new Lot { Origin = new Attributed(), Quality = 1 }; + var items = new ItemManager(cache, ledger, settings, _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + + var hullRef = items.ItemData.RefOf(items.ItemData.GetByName("Hull")); + var shooterHull = new EquippableItem { Data = hullRef, Durability = 100000, Lot = 1 }; + var shooter = new Ship(items, zone, shooterHull, new EntitySettings()); + + var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var gun = new EquippableItem { Data = gunRef, Durability = 1, Lot = 2 }; + Assert.True(shooter.TryEquip(gun, new int2(0, 0))); + var weaponItem = shooter.Equipment.Single(e => e.EquippableItem == gun); + var weapon = (InstantWeapon) weaponItem.Behaviors.Single(b => b is Weapon); + + var targetingRef = items.ItemData.RefOf(items.ItemData.GetByName("Targeting")); + var targeting = new EquippableItem { Data = targetingRef, Durability = 1, Lot = 3 }; + Assert.True(shooter.TryFindSpace(targeting, out var tpos)); + Assert.True(shooter.TryEquip(targeting, tpos)); + + var targetHull = new EquippableItem { Data = hullRef, Durability = 100000, Lot = 4 }; + var target = new Ship(items, zone, targetHull, new EntitySettings()); + // A target with no non-hull equipment never runs TryEquip, so Entity's _orderedEquipment (only ever + // populated there) stays null and Entity.Update NREs on the very first tick -- give it an inert item + // purely so that array gets initialized, the same reason FireControlCut5Tests' fixtures always equip + // a target gun. + var targetGunRef = items.ItemData.RefOf(items.ItemData.GetByName("Gun")); + var targetGun = new EquippableItem { Data = targetGunRef, Durability = 1, Lot = 5 }; + Assert.True(target.TryEquip(targetGun, new int2(0, 0))); + + zone.Entities.Add(shooter); + zone.Entities.Add(target); + shooter.Activate(); + target.Activate(); + + shooter.Position = float3.zero; + target.Position = float3(0, 0, targetRange); + shooter.Target.Value = target; + shooter.EntityInfoGathered[target] = 1f; + shooter.SetIff(target, true); + + zone.Update(0f); // warm up resolved stats + + return new Engagement { Items = items, Zone = zone, Shooter = shooter, Target = target, WeaponItem = weaponItem, Weapon = weapon }; + } + + // ---- 6.1: a shot's dice belong to the shot (Soul finding 6). ---- + + // A fixed fight, run twice from the same zone identity (CombatSeed comes from the fixed GalaxyZone name + // "Test", shared by both engagements), with an arbitrary number of unrelated draws from ItemManager.Random + // between shots in the second run. Outcomes must be identical shot-for-shot. Mutation: restore + // `shot.Source.ItemManager.Random` as Commit's generator -- the unrelated draws below then advance the + // shared stream Commit reads from, so the second run's hit/cell sequence diverges from the first's. This + // is the test Soul's own hermetic-fixture probe could never be (docs/fire-control-cut.md, 6.1): a fixture + // that never draws anything unrelated cannot see a shared-stream defect. + [Fact] + public void SameFightRollsSameThroughUnrelatedDraws() + { + var settings = TestSettings(); + + List<(bool hit, int2 cell)> RunFight(Action unrelatedDraws) + { + var e = Build(settings, damage: 10, velocity: 0, accuracy: 1, resolution: 1, tracking: 100000, targetRange: 100); + var outcomes = new List<(bool, int2)>(); + e.Zone.ShotResolved.Subscribe(o => outcomes.Add((o.Hit, o.Cell))); + for (var i = 0; i < 8; i++) + { + unrelatedDraws?.Invoke(e.Items, i); + FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + e.Zone.Update(.01f); // flight time 0 (velocity 0) -> commits and resolves in this one call + } + return outcomes; + } + + var baseline = RunFight(null); + // A different, growing number of unrelated draws before each shot -- exactly "how many draws came + // before it" perturbing a shared stream would be sensitive to. + var perturbed = RunFight((items, i) => { for (var k = 0; k < i * 3 + 1; k++) items.Random.NextFloat(); }); + + Assert.Equal(baseline.Count, perturbed.Count); + Assert.True(baseline.Count > 0); + Assert.Equal(baseline, perturbed); + } + + // A shot's outcome is a function of its own id: firing many shots at an identical, unmoving target (same + // frozen payload in every way but ShotId, which increments per shot) must not always land on the same + // cell. Mutation: drop ShotId from the seed -- every shot in a zone would then build the exact same local + // generator, so every one of these draws the same cell every time (no variety at all across the run). + [Fact] + public void ShotIdDecidesTheDie() + { + var settings = TestSettings(); + var e = Build(settings, damage: 10, velocity: 0, accuracy: 1, resolution: 1, tracking: 100000, targetRange: 100); + + var cells = new List(); + e.Zone.ShotResolved.Subscribe(o => { if (o.Hit) cells.Add(o.Cell); }); + + for (var i = 0; i < 12; i++) + { + FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + e.Zone.Update(.01f); + } + + Assert.True(cells.Count > 1); + Assert.True(cells.Distinct().Count() > 1, "Every shot landed on the same cell -- ShotId is not reaching the seed."); + } + + // ---- 6.2: airburst resolves in the simulation (Soul finding 5). ---- + + // An airburst shot resolves via Splash, and Splash does not gate on the discrete hit roll at all -- it + // damages everything in radius unconditionally (Cut 4's rule). Accuracy 0 pins PBase (and so Commit's hit) + // to false with no dependence on the random draw, so a normal discrete shot would apply no damage + // whatsoever (Apply's own `if (!shot.Outcome.Hit) return;`). An airburst shot must still deal its area + // damage. Mutation: call Apply as well as Splash -- harmless here (Apply still no-ops on a miss), so this + // test alone does not catch that mutation; AirburstAndDiscreteNeverDoubleUp below does, with a guaranteed + // hit where an extra Apply call is not a no-op. + [Fact] + public void AirburstSplashesEvenOnAGuaranteedMiss() + { + var settings = TestSettings(); + var e = Build(settings, damage: 500, velocity: 0, accuracy: 0, resolution: 1, tracking: 100000, + targetRange: 50, airburst: true, airburstRange: 100); + + var before = e.Target.Hull.Durability; + FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + e.Zone.Update(.01f); + + Assert.True(e.Target.Hull.Durability < before, "An airburst shot must splash regardless of the discrete hit roll."); + } + + // The double-application Soul was told to hunt for: with a guaranteed hit (accuracy 1), an airburst shot's + // total damage must equal a bare Splash call's own damage -- not more. Mutation: call Apply as well as + // Splash at arrival -- Apply's own discrete cell hit would land on top of Splash's area damage, so the + // airburst shot's total damage exceeds a lone Splash call's. + [Fact] + public void AirburstAndDiscreteNeverDoubleUp() + { + var settings = TestSettings(); + + var e = Build(settings, damage: 10, velocity: 0, accuracy: 1, resolution: 1, tracking: 100000, + targetRange: 50, airburst: true, airburstRange: 100); + var before = e.Target.Hull.Durability; + FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + e.Zone.Update(.01f); + var actualDelta = before - e.Target.Hull.Durability; + + // A fresh, identically-shaped target, damaged by one bare Splash call with the same parameters + // FireControl.Fire freezes for this weapon (BurstPosition, for a stationary velocity-0 target, is + // exactly its own position -- PredictedIntercept falls back to target.Position below weapon.Velocity's + // .01f floor). + var e2 = Build(settings, damage: 10, velocity: 0, accuracy: 1, resolution: 1, tracking: 100000, + targetRange: 50, airburst: true, airburstRange: 100); + var before2 = e2.Target.Hull.Durability; + FireControl.Splash(e2.Zone, e2.Target.Position, 100, 10, DamageType.Kinetic); + var expectedDelta = before2 - e2.Target.Hull.Durability; + + Assert.True(expectedDelta > 0); + Assert.Equal(expectedDelta, actualDelta, 3); + } + + // The other side: a non-airburst shot must never splash, even one that lands exactly on its own frozen + // burst position at zero range (a stationary target, so BurstPosition == the target's own position at + // arrival) -- the zero-radius edge case a careless "splash unconditionally" mutant would still pass + // through, since distance 0 is never greater than radius 0. Accuracy 0 pins the discrete roll to a + // guaranteed miss, so the correct path (Apply, gated on Outcome.Hit) deals no damage at all. Mutation: + // splash unconditionally at arrival instead of gating on BurstRadius -- Splash does not check Hit, so it + // would still deal damage even though this shot never carried the Airburst flag. + [Fact] + public void NonAirburstNeverSplashes() + { + var settings = TestSettings(); + var e = Build(settings, damage: 1000, velocity: 0, accuracy: 0, resolution: 1, tracking: 100000, + targetRange: 50, airburst: false); + + var before = e.Target.Hull.Durability; + FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter); + e.Zone.Update(.01f); + + Assert.Equal(before, e.Target.Hull.Durability); + } + + // ---- negative: ItemManager.Random no longer appears in FireControl.cs; Airburst no longer appears + // anywhere under Assets/Scripts/Gameplay (Projectile.cs's fields and ProjectileManager.cs's write-back are + // deleted, not merely unused). Enforced by tests/mutation_tests_fire_control_cut6.sh's negative-grep step, + // not restated here as a source-scanning unit test. +} From 1a1cb8f3d15f9a834e3e34090701e3f089cb1e5c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 18:41:38 +0200 Subject: [PATCH 2/2] Fire control Cut 6b: mutation harness, and comments that leaked past the negative greps tests/mutation_tests_fire_control_cut6.sh, modelled on Cut 5's harness: a no-op control, four mutations (6.1's shared-stream generator and dropped-ShotId seed; 6.2's double-application and unconditional-splash), byte-exact I/O with sha256-verified restore after every mutation, and the two negative greps the Cut 6 spec names. All five mutations behave as declared and the tree-clean verdict is PASS. Fixes two of Commit's and Projectile's own explanatory comments that quoted the literal strings the negative greps check for (ItemManager.Random, Airburst), which the first harness run caught as false failures -- reworded, no behavior change. Co-Authored-By: Claude Sonnet 5 --- Assets/Scripts/Gameplay/Weapons/Projectile.cs | 7 +- Assets/Scripts/ServerShared/FireControl.cs | 3 +- tests/mutation_tests_fire_control_cut6.sh | 289 ++++++++++++++++++ 3 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 tests/mutation_tests_fire_control_cut6.sh diff --git a/Assets/Scripts/Gameplay/Weapons/Projectile.cs b/Assets/Scripts/Gameplay/Weapons/Projectile.cs index b76fa6b0f..dd83d0228 100644 --- a/Assets/Scripts/Gameplay/Weapons/Projectile.cs +++ b/Assets/Scripts/Gameplay/Weapons/Projectile.cs @@ -5,9 +5,10 @@ using static CultMath.math; // Cut 3 (docs/fire-control-cut.md): the raycast, shield branch and SendHit are deleted -- FireControl already // decided this shot's fate before this object was ever spawned (R8). What is left is pure flight-path // presentation: fly, and disappear at Range or ShotId's resolution, whichever comes first. -// Cut 6b, 6.2: airburst resolves in the simulation now (FireControl.Step calls Splash instead of Apply at -// arrival) -- a MonoBehaviour calling Splash would be exactly the authority Cut 3 spent itself deleting, so -// AirburstDistance/AirburstRange are gone. This object's job stays fly-and-disappear. +// Cut 6b, 6.2: the flak-round blast now resolves in the simulation (FireControl.Step calls Splash instead of +// Apply at arrival) -- a MonoBehaviour calling Splash would be exactly the authority Cut 3 spent itself +// deleting, so the blast-distance/blast-radius fields this object used to carry for that are gone. This +// object's job stays fly-and-disappear. public class Projectile : MonoBehaviour { public TrailRenderer Trail; diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 6bb65be55..79a4318fd 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -288,7 +288,8 @@ public static class FireControl private static ShotOutcome Commit(Zone zone, PendingShot shot, float now) { // Cut 6b, 6.1 (Soul finding 6): a shot's dice belong to the shot, not to whatever else happened to - // draw from ItemManager.Random first. A pure function of (zone identity, shot id) -- the `| 1u` guards + // draw from the engine-wide shared generator first. A pure function of (zone identity, shot id) -- + // the `| 1u` guards // the degenerate zero seed -- so two runs of the same fight from the same galaxy seed roll identically // no matter what the UI drew from the shared stream in between. This generator is local and dies with // the call: nothing outside Commit may seed or advance a combat draw, and Commit may not read or write diff --git a/tests/mutation_tests_fire_control_cut6.sh b/tests/mutation_tests_fire_control_cut6.sh new file mode 100644 index 000000000..175769cc4 --- /dev/null +++ b/tests/mutation_tests_fire_control_cut6.sh @@ -0,0 +1,289 @@ +#!/usr/bin/env bash +# Mutation tests for docs/fire-control-cut.md's Cut 6b ("the dice stop being shared, and the flak cannon works +# again"). +# +# Four mutations, each against tests/Aetheria.Shared.Tests/FireControlCut6Tests.cs, plus a no-op control and a +# negative-grep step: +# +# 1. 6.1 SameFightRollsSameThroughUnrelatedDraws -- restore Commit's generator to the shared +# ItemManager.Random stream (read AND write-back; CultMath.Random is a struct, so the old shared-stream +# behaviour needs both halves, not just the read). +# 2. 6.1 ShotIdDecidesTheDie -- drop ShotId from the local generator's seed. +# 3. 6.2 AirburstAndDiscreteNeverDoubleUp -- call Apply as well as Splash at arrival. +# 4. 6.2 NonAirburstNeverSplashes -- splash unconditionally instead of gating on BurstRadius. +# +# A no-op control (a byte-identical rewrite of the target file through this script's own read/write path) +# proves the mechanism itself is transparent before any real mutation is trusted. Modelled on +# tests/mutation_tests_fire_control_cut5.sh, the good example: byte-exact I/O, sha256-verified restore after +# every single mutation, and an explicit tree-clean verdict line at exit. +# +# Usage: +# tests/mutation_tests_fire_control_cut6.sh +# +# Every mutation is reversed (byte-exact, from an on-disk copy) before the script exits, including on failure +# or interrupt, and every restore is verified against a sha256 recorded before any mutation ran: the tree- +# clean verdict at the end states PASS/FAIL explicitly rather than leaving a reader to infer it. A SIGKILL of +# the whole process group is the one termination bash cannot trap at all -- verify the tree independently +# after a run that was killed that hard. + +set -u + +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +CULTLIB_ROOT="$1" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +TEST_PROJECT="$REPO_ROOT/tests/Aetheria.Shared.Tests" + +FIRE_CONTROL_CS="$REPO_ROOT/Assets/Scripts/ServerShared/FireControl.cs" + +# --- byte-exact backup/restore: preserves line endings exactly, no text-mode translation. Every target file's +# pre-mutation sha256 is recorded once here, before any mutation touches it; every restore below -- per- +# mutation and at exit -- re-hashes and refuses to let a mismatch pass silently (docs/fire-control-cut.md Cut +# 5b.3's own lesson: a harness that can leak an un-restored mutation into the tree produces fictional +# verdicts). --- +declare -A ORIGINALS +declare -A ORIGINAL_HASH +FILES=("$FIRE_CONTROL_CS") +BACKUP_DIR="$(mktemp -d)" + +hash_file() { + sha256sum "$1" 2>/dev/null | awk '{print $1}' +} + +for f in "${FILES[@]}"; do + base="$(basename "$f")" + cp -p "$f" "$BACKUP_DIR/$base.orig" + ORIGINALS["$f"]="$BACKUP_DIR/$base.orig" + ORIGINAL_HASH["$f"]="$(hash_file "$f")" +done + +restore_and_verify() { + local file="$1" + cp -p "${ORIGINALS[$file]}" "$file" + local actual + actual="$(hash_file "$file")" + if [ "$actual" != "${ORIGINAL_HASH[$file]}" ]; then + echo "" >&2 + echo "FATAL: restoring $file did not reproduce its pre-mutation hash -- aborting." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$file]}" >&2 + echo " actual sha256: $actual" >&2 + exit 1 + fi +} + +TREE_CLEAN_OK=1 +TREE_VERDICT_DONE=0 + +verify_tree_clean() { + if [ "$TREE_VERDICT_DONE" = "1" ]; then return; fi + local f actual + for f in "${FILES[@]}"; do + cp -p "${ORIGINALS[$f]}" "$f" 2>/dev/null + actual="$(hash_file "$f")" + if [ "$actual" != "${ORIGINAL_HASH[$f]}" ]; then + echo "FATAL: $f is NOT byte-identical to how this script found it." >&2 + echo " expected sha256: ${ORIGINAL_HASH[$f]}" >&2 + echo " actual sha256: $actual" >&2 + TREE_CLEAN_OK=0 + fi + done + echo "" + if [ "$TREE_CLEAN_OK" = "1" ]; then + echo "=== tree-clean verdict: PASS -- every target file is byte-identical to how this script found it ===" + else + echo "=== tree-clean verdict: FAIL -- see FATAL lines above; the working tree is contaminated ===" + fi + TREE_VERDICT_DONE=1 +} +trap verify_tree_clean EXIT INT TERM + +FAILURES=() + +# replace_unique FILE ANCHOR REPLACEMENT +# Anchor must occur exactly once (byte-exact match via perl, not sed's line-oriented rewriting, so a +# multi-line anchor is matched as literal text). Writes the mutated content back byte-exact. +replace_unique() { + local file="$1" anchor="$2" replacement="$3" + local count + count=$(perl -0777 -e ' + my ($anchor, $file) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $n = () = $text =~ /\Q$anchor\E/g; + print $n; + ' "$anchor" "$file") + if [ "$count" != "1" ]; then + echo "ERROR: $file: anchor must occur exactly once, found $count" >&2 + echo "--- anchor ---" >&2 + echo "$anchor" >&2 + return 1 + fi + perl -0777 -e ' + my ($file, $anchor, $replacement) = @ARGV; + local $/; open(my $fh, "<:raw", $file) or die $!; + my $text = <$fh>; close $fh; + my $qa = quotemeta($anchor); + $text =~ s/$qa/$replacement/; + open(my $out, ">:raw", $file) or die $!; + print $out $text; close $out; + ' "$file" "$anchor" "$replacement" +} + +ARTIFACTS_PATH="$(mktemp -d)" + +# run_test TEST_FQN -> 0 (passed) or 1 (failed/errored) +run_test() { + local test="$1" + local out + out=$(dotnet test "$TEST_PROJECT" -p:CultLibRoot="$CULTLIB_ROOT" --artifacts-path "$ARTIFACTS_PATH" --filter "FullyQualifiedName~$test" 2>&1) + if echo "$out" | grep -q "Passed!" && ! echo "$out" | grep -q "Failed: [1-9]"; then + return 0 + fi + LAST_OUTPUT="$out" + return 1 +} + +# check_mutation NAME FILE TEST EXPECT("red"|"green") -- applies whatever mutation the caller already staged +# via replace_unique calls made just before invoking this, runs TEST, restores FILE, and judges. Used by the +# single-anchor mutations below directly; the one multi-edit mutation (restoring the shared-stream generator) +# calls replace_unique twice itself before delegating here. +judge_mutation() { + local name="$1" file="$2" test="$3" expect="$4" + if run_test "$test"; then + passed=1 + else + passed=0 + fi + restore_and_verify "$file" # restore immediately, before judging, so a crash still leaves a clean tree + + if [ "$expect" = "green" ]; then + if [ "$passed" = "1" ]; then + echo "OK: $test passed under a no-op mutation, as expected" + else + FAILURES+=("$name: expected green (test passing), got failure") + echo "$LAST_OUTPUT" | tail -40 + fi + else + if [ "$passed" = "0" ]; then + echo "OK: $test went red under the mutation, as expected" + else + FAILURES+=("$name: expected red (mutant killed), but $test still passed") + fi + fi +} + +# check_mutation NAME FILE ANCHOR MUTATED TEST EXPECT("red"|"green") -- single-anchor convenience wrapper. +check_mutation() { + local name="$1" file="$2" anchor="$3" mutated="$4" test="$5" expect="$6" + echo "" + echo "=== $name (expect $expect) ===" + if ! replace_unique "$file" "$anchor" "$mutated"; then + FAILURES+=("$name: anchor replacement failed") + restore_and_verify "$file" + return + fi + judge_mutation "$name" "$file" "$test" "$expect" +} + +# --- No-op control: a byte-identical round trip through this script's own replace_unique path, proving the +# anchor/replace/restore mechanism is transparent before any real mutation is trusted. --- +check_mutation \ + "control (no-op round trip)" \ + "$FIRE_CONTROL_CS" \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u);' \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u);' \ + "FireControlCut6Tests.SameFightRollsSameThroughUnrelatedDraws" \ + "green" + +# --- 6.1: a shot's dice belong to the shot. Mutation: restore Commit's generator to the shared +# ItemManager.Random stream -- both the read and the write-back, since CultMath.Random is a struct and the old +# shared-stream behaviour depended on writing the advanced copy back for the next Commit to see. Unrelated +# draws the test makes between shots then perturb the very stream Commit reads from. --- +echo "" +echo "=== 6.1 Commit must not read or write the shared ItemManager.Random stream (expect red) ===" +if replace_unique "$FIRE_CONTROL_CS" \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u);' \ + 'var random = shot.Source.ItemManager.Random;' \ +&& replace_unique "$FIRE_CONTROL_CS" \ + 'return MakeOutcome(shot, hit, shielded, shieldBroken, cell, aimed, now);' \ + 'shot.Source.ItemManager.Random = random; + return MakeOutcome(shot, hit, shielded, shieldBroken, cell, aimed, now);'; then + judge_mutation "6.1 shared-stream generator" "$FIRE_CONTROL_CS" \ + "FireControlCut6Tests.SameFightRollsSameThroughUnrelatedDraws" "red" +else + FAILURES+=("6.1 shared-stream generator: anchor replacement failed") + restore_and_verify "$FIRE_CONTROL_CS" +fi + +# --- 6.1: the roll is a function of the shot's own id. Mutation: drop ShotId from the seed -- every shot in a +# zone then builds the exact same local generator every time. --- +check_mutation \ + "6.1 ShotId must reach the seed" \ + "$FIRE_CONTROL_CS" \ + 'var random = new Random((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u);' \ + 'var random = new Random((zone.CombatSeed * 2654435761u) | 1u);' \ + "FireControlCut6Tests.ShotIdDecidesTheDie" \ + "red" + +# --- 6.2: airburst resolves via Splash instead of Apply, never both. Mutation: call Apply as well as Splash at +# arrival -- the double-application Soul was told to hunt for. --- +check_mutation \ + "6.2 an airburst shot must not also Apply a discrete hit" \ + "$FIRE_CONTROL_CS" \ + $' if (shot.BurstRadius > 0f) Splash(zone, shot.BurstPosition, shot.BurstRadius, shot.Damage, shot.DamageType);\r\n else Apply(shot);' \ + $' if (shot.BurstRadius > 0f) Splash(zone, shot.BurstPosition, shot.BurstRadius, shot.Damage, shot.DamageType);\r\n Apply(shot);' \ + "FireControlCut6Tests.AirburstAndDiscreteNeverDoubleUp" \ + "red" + +# --- 6.2: the other side. Mutation: splash unconditionally instead of gating on BurstRadius -- Splash does not +# check Hit, so a shot that never carried the Airburst flag would still deal area damage. --- +check_mutation \ + "6.2 a non-airburst shot must never splash" \ + "$FIRE_CONTROL_CS" \ + $' if (shot.BurstRadius > 0f) Splash(zone, shot.BurstPosition, shot.BurstRadius, shot.Damage, shot.DamageType);\r\n else Apply(shot);' \ + ' Splash(zone, shot.BurstPosition, shot.BurstRadius, shot.Damage, shot.DamageType);' \ + "FireControlCut6Tests.NonAirburstNeverSplashes" \ + "red" + +echo "" +echo "=== negative greps ===" +if grep -q "ItemManager.Random" "$FIRE_CONTROL_CS"; then + FAILURES+=("negative grep: ItemManager.Random still appears in FireControl.cs") + echo "FAIL: ItemManager.Random appears in FireControl.cs" +else + echo "OK: ItemManager.Random does not appear in FireControl.cs" +fi + +if grep -rq "Airburst" "$REPO_ROOT/Assets/Scripts/Gameplay"; then + FAILURES+=("negative grep: Airburst still appears under Assets/Scripts/Gameplay") + echo "FAIL: Airburst appears under Assets/Scripts/Gameplay" + grep -rn "Airburst" "$REPO_ROOT/Assets/Scripts/Gameplay" +else + echo "OK: Airburst does not appear anywhere under Assets/Scripts/Gameplay" +fi + +echo "" +verify_tree_clean # explicit call: the tree-clean verdict is part of THIS run's own summary, not only + # something printed later at exit (the trap's own call is a no-op after this one runs -- + # see TREE_VERDICT_DONE above -- and remains the safety net for an interrupted run). + +if [ "${#FAILURES[@]}" -gt 0 ]; then + echo "" + echo "=== FAILURES ===" + for f in "${FAILURES[@]}"; do + echo "- $f" + done +fi + +if [ "${#FAILURES[@]}" -gt 0 ] || [ "$TREE_CLEAN_OK" != "1" ]; then + echo "" + echo "RESULT: FAILED -- mutations: $([ "${#FAILURES[@]}" -gt 0 ] && echo "${#FAILURES[@]} failure(s)" || echo "all behaved as declared"), tree-clean: $([ "$TREE_CLEAN_OK" = "1" ] && echo PASS || echo FAIL)" + exit 1 +fi + +echo "RESULT: All mutations behaved as declared. tree-clean: PASS" +exit 0