diff --git a/Assets/Scripts/Gameplay/HullCollider.cs b/Assets/Scripts/Gameplay/HullCollider.cs index 34d005ade..bdd417e8e 100644 --- a/Assets/Scripts/Gameplay/HullCollider.cs +++ b/Assets/Scripts/Gameplay/HullCollider.cs @@ -1,79 +1,17 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using UniRx; -using CultMath; -using CultMath.UnityBridge; -using static CultMath.math; using UnityEngine; -using float2 = CultMath.float2; +using CultMath.UnityBridge; -// Cut 3 (docs/fire-control-cut.md) FORK, reported rather than worked around silently: the map's Cut 3 deletion -// list calls for Hit, Splash, SendHit and SendSplash to go away here outright. They cannot, yet, without -// breaking the build -- ConstantLaser.cs, ConstantLightning.cs, ConstantParticleWeapon.cs, HitscanEffect.cs -// and Mine.cs (Cut 4's "unused kinds," R9) still call hull.SendHit/SendSplash from their own live Physics -// queries, and Cut 4 is the cut that migrates them. Deleting these methods now is a compile break in -// out-of-scope files, not a behaviour change in this cut's own scope. -// -// What Cut 3 actually owns and has delivered: nothing in Assets/Scripts/Gameplay/Weapons/{Projectile, -// GuidedProjectile,Laser,Lightning}.cs calls SendHit/SendSplash any more (see those files), and -// EntityInstance.cs no longer subscribes to Hit/Splash at all -- so for the four weapon kinds this cut owns, -// these events have no subscriber and decide nothing. They fire into the void until Cut 4 deletes them -// together with their last remaining callers. OnCollisionEnter stays regardless: ship-on-ship collision -// impulse is a deferred Unity-physics surface, not part of fire control. +// Cut 4 (docs/fire-control-cut.md): Hit, Splash, SendHit and SendSplash are deleted -- their last callers +// (ConstantLaser, ConstantLightning, ConstantParticleWeapon, HitscanEffect, Mine) are gone too (see those +// files and FireControl.Splash). Nothing decides or applies damage through a Unity collider any more (R8): +// this component is now purely a physics surface for ship-on-ship collision impulse and Mine's own proximity +// arming query (Q7), neither of which is hit detection. public class HullCollider : MonoBehaviour { - public Subject Hit = new Subject(); - public Subject Splash = new Subject(); - public Entity Entity { get; set; } - public void SendHit(float damage, float penetration, float spread, DamageType damageType, Entity source, Vector2 texCoord, Vector3 direction) - { - Hit.OnNext(new HullHitEventArgs - { - Damage = damage, - Penetration = penetration, - Spread = spread, - DamageType = damageType, - Source = source, - TexCoord = texCoord.ToCultMath(), - Direction = direction.ToCultMath() - }); - } - - public void SendSplash(float damage, DamageType damageType, Entity source, Vector3 direction) - { - Splash.OnNext(new HullSplashEventArgs - { - Damage = damage, - DamageType = damageType, - Source = source, - Direction = direction.ToCultMath() - }); - } - private void OnCollisionEnter(Collision other) { Entity.Velocity += other.impulse.ToCultMath().xz / Time.deltaTime; } - - public class HullHitEventArgs - { - public float Damage; - public float Penetration; - public float Spread; - public DamageType DamageType; - public Entity Source; - public float2 TexCoord; - public float3 Direction; - } - - public class HullSplashEventArgs - { - public float Damage; - public DamageType DamageType; - public Entity Source; - public float3 Direction; - } } diff --git a/Assets/Scripts/Gameplay/Weapons/ConstantLaser.cs b/Assets/Scripts/Gameplay/Weapons/ConstantLaser.cs index 002b4a367..23fb7216e 100644 --- a/Assets/Scripts/Gameplay/Weapons/ConstantLaser.cs +++ b/Assets/Scripts/Gameplay/Weapons/ConstantLaser.cs @@ -1,8 +1,11 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; -using static CultMath.math; +// Cut 4 (docs/fire-control-cut.md): the raycast, shield branch and SendHit are deleted -- FireControl already +// rolls this weapon's damage once per GameplaySettings.BeamResolveInterval (ConstantWeapon.Execute) before +// this beam is ever drawn (R8). What is left is pure endpoint presentation, the same convention Laser.cs +// (Cut 3) uses for a discrete shot: draw to the target's current position, or out to Range with no target. public class ConstantLaser : MonoBehaviour { public AnimationCurve StartCurve; @@ -13,13 +16,10 @@ public class ConstantLaser : MonoBehaviour public float FadeDuration; public float CycleDuration; public LineRenderer LineRenderer; - - public float Damage { get; set; } - public float Penetration { get; set; } - public float Spread { get; set; } - public DamageType DamageType { get; set; } + public Entity SourceEntity { get; set; } public float Range { get; set; } + public Transform TargetTransform { get; set; } private float _intensity; private float _stopIntensity; @@ -70,45 +70,9 @@ public class ConstantLaser : MonoBehaviour } LineRenderer.SetPosition(0, transform.position); - bool hitFound = false; - foreach (var hit in Physics.RaycastAll(new Ray(transform.position, transform.forward), Range, 1 | (1 << 17))) - { - var shield = hit.collider.GetComponent(); - if (shield) - { - var shieldBehavior = shield.Entity.Shield; - var shieldActive = shieldBehavior != null && shieldBehavior.Item.Active.Value; - var shieldAbsorbs = shieldActive && shieldBehavior.CanTakeHit(DamageType, Damage); - // F5 (docs/stats-and-power-cut.md, Soul pass 2026-09-19): CanTakeHit is a pure query now -- read - // once into shieldAbsorbs, and break the shield exactly once, right here, at the point this hit - // is actually decided to route past it (to the hull collider RaycastAll returns further down - // this same loop) instead of being absorbed. The hull branch below re-queries CanTakeHit safely - // -- it is side-effect-free -- and will see Broken already true. - if (shieldActive && !shieldAbsorbs) shieldBehavior.Break(); - if (!shieldAbsorbs) continue; - if (shield.Entity != SourceEntity) - { - shieldBehavior.TakeHit(DamageType, Damage); - shield.ShowHit(hit.point, sqrt(Damage)); - LineRenderer.SetPosition(1, hit.point); - hitFound = true; - break; - } - } - var hull = hit.collider.GetComponent(); - if (hull && !(hull.Entity.Shield != null && hull.Entity.Shield.Item.Active.Value && hull.Entity.Shield.CanTakeHit(DamageType, Damage))) - { - if (hull.Entity != SourceEntity) - { - hull.SendHit(Damage * Time.deltaTime, Penetration, Spread, DamageType, SourceEntity, hit.textureCoord, transform.forward); - LineRenderer.SetPosition(1, hit.point); - hitFound = true; - break; - } - } - } - if(!hitFound) - LineRenderer.SetPosition(1, transform.position + transform.forward * Range); + LineRenderer.SetPosition(1, TargetTransform != null + ? TargetTransform.position + : transform.position + transform.forward * Range); } public void Stop() diff --git a/Assets/Scripts/Gameplay/Weapons/ConstantLaserManager.cs b/Assets/Scripts/Gameplay/Weapons/ConstantLaserManager.cs index 351314e61..039e9344b 100644 --- a/Assets/Scripts/Gameplay/Weapons/ConstantLaserManager.cs +++ b/Assets/Scripts/Gameplay/Weapons/ConstantLaserManager.cs @@ -19,10 +19,9 @@ public class ConstantLaserManager : ConstantWeaponEffectManager t.SetParent(barrel); t.forward = barrel.forward; t.position = barrel.position; - p.Damage = item.Evaluate(data.Damage); - p.Penetration = item.Evaluate(data.Penetration); - p.Spread = item.Evaluate(data.DamageSpread); - p.DamageType = data.DamageType; + // Cut 4 (docs/fire-control-cut.md): FireControl already rolls this weapon's damage; the presentation + // only needs to know where to draw the beam. + p.TargetTransform = target != null ? target.transform : null; _lasers.Add(item, p); } diff --git a/Assets/Scripts/Gameplay/Weapons/ConstantLightning.cs b/Assets/Scripts/Gameplay/Weapons/ConstantLightning.cs index 3088c32b7..cbf07abd7 100644 --- a/Assets/Scripts/Gameplay/Weapons/ConstantLightning.cs +++ b/Assets/Scripts/Gameplay/Weapons/ConstantLightning.cs @@ -1,8 +1,12 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; -using static CultMath.math; +// Cut 4 (docs/fire-control-cut.md): the SphereCast, shield branch and SendHit are deleted -- FireControl +// already rolls this weapon's damage once per GameplaySettings.BeamResolveInterval (ConstantWeapon.Execute) +// before this bolt is ever drawn (R8). What is left is pure endpoint presentation: fixed to the target's +// current position when there is one, out to Range otherwise -- the same convention Lightning.cs (Cut 3) +// uses for a discrete shot. public class ConstantLightning : MonoBehaviour { public LightningCompute Lightning; @@ -11,14 +15,11 @@ public class ConstantLightning : MonoBehaviour public float StartWidth = 1; public float EndWidth = 1; public float FadeDuration; - + public Transform Barrel { get; set; } - public float Damage { get; set; } - public float Penetration { get; set; } - public float Spread { get; set; } - public DamageType DamageType { get; set; } public EntityInstance Source { get; set; } public float Range { get; set; } + public Transform TargetTransform { get; set; } private bool _stopping; private float _startTime; @@ -50,31 +51,10 @@ public class ConstantLightning : MonoBehaviour Lightning.EndWidth = EndWidth; } - Lightning.FixedEndpoint = false; - var hits = Physics.SphereCastAll(Barrel.position, HitRadius, Barrel.forward, Range, 1 | (1 << 17)); - foreach (var hit in hits) - { - var shield = hit.collider.GetComponent(); - if (shield && (shield.Entity.Shield != null && shield.Entity.Shield.Item.Active.Value && shield.Entity.Shield.CanTakeHit(DamageType, Damage))) - { - if (shield.Entity == Source.Entity) continue; - shield.Entity.Shield.TakeHit(DamageType, Damage * Time.deltaTime); - shield.ShowHit(hit.point, sqrt(Damage)); - } - var hull = hit.collider.GetComponent(); - if (hull && !(hull.Entity.Shield != null && hull.Entity.Shield.Item.Active.Value && hull.Entity.Shield.CanTakeHit(DamageType, Damage))) - { - if (hull.Entity == Source.Entity) continue; - hull.SendHit(Damage * Time.deltaTime, Penetration, Spread, DamageType, Source.Entity, hit.textureCoord, Barrel.forward); - } - - Lightning.FixedEndpoint = true; - Lightning.EndPosition = hit.point; - - break; - } - if(!Lightning.FixedEndpoint) - Lightning.EndPosition = Barrel.position + Barrel.forward * Range; + Lightning.FixedEndpoint = TargetTransform != null; + Lightning.EndPosition = TargetTransform != null + ? TargetTransform.position + : Barrel.position + Barrel.forward * Range; Lightning.StartPosition = Barrel.position; } diff --git a/Assets/Scripts/Gameplay/Weapons/ConstantLightningManager.cs b/Assets/Scripts/Gameplay/Weapons/ConstantLightningManager.cs index 77a1be884..111df4433 100644 --- a/Assets/Scripts/Gameplay/Weapons/ConstantLightningManager.cs +++ b/Assets/Scripts/Gameplay/Weapons/ConstantLightningManager.cs @@ -16,11 +16,10 @@ public class ConstantLightningManager : ConstantWeaponEffectManager var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y]; var barrel = source.GetBarrel(hp); p.Barrel = barrel; - p.Damage = item.Evaluate(data.Damage); p.Range = item.Evaluate(data.Range); - p.Penetration = item.Evaluate(data.Penetration); - p.Spread = item.Evaluate(data.DamageSpread); - p.DamageType = data.DamageType; + // Cut 4 (docs/fire-control-cut.md): FireControl already rolls this weapon's damage; the presentation + // only needs to know where to draw the bolt. + p.TargetTransform = target != null ? target.transform : null; _bolts.Add(item, p); } diff --git a/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeapon.cs b/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeapon.cs index f09d10ed4..e1d7e11d5 100644 --- a/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeapon.cs +++ b/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeapon.cs @@ -4,19 +4,19 @@ using System.Collections.Generic; using System.Linq; using UnityEngine; +// Cut 4 (docs/fire-control-cut.md): the trigger-collider plumbing and SendSplash are deleted -- FireControl +// already rolls this weapon's damage once per GameplaySettings.BeamResolveInterval (ConstantWeapon.Execute) +// before these particles ever collide with anything (R8). What is left is pure visual emission; nothing here +// decides or applies damage any more. public class ConstantParticleWeapon : MonoBehaviour { public ParticleSystem[] Particles; - - public float Damage { get; set; } - public DamageType DamageType { get; set; } + public EntityInstance Source { get; set; } public EntityInstance Target { get; set; } private bool _stopping; private float _emission; - private List _collisionParticles = new List(); - private HullCollider _hull; private void Start() { @@ -38,18 +38,10 @@ public class ConstantParticleWeapon : MonoBehaviour main.simulationSpace = ParticleSystemSimulationSpace.Custom; main.customSimulationSpace = Source.LocalSpace; } - + var trigger = Particles[0].trigger; while(trigger.colliderCount > 0) trigger.RemoveCollider(0); - - if (Target == null) return; - - foreach (var collider in Target.HullColliders) - { - _hull = collider; - trigger.AddCollider(collider.GetComponent()); - } } private void Update() @@ -62,21 +54,6 @@ public class ConstantParticleWeapon : MonoBehaviour } } - private void OnParticleTrigger() - { - if (Target == null || !_hull) return; - _collisionParticles.Clear(); - Particles[0].GetTriggerParticles(ParticleSystemTriggerEventType.Enter, _collisionParticles); - if(_collisionParticles.Count > 0) - { - _hull.SendSplash( - Damage * Time.deltaTime, - DamageType, - Source.Entity, - (transform.position - Target.transform.position).normalized); - } - } - public void Stop() { foreach(var p in Particles) diff --git a/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeaponManager.cs b/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeaponManager.cs index 6326330e3..8b0095975 100644 --- a/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeaponManager.cs +++ b/Assets/Scripts/Gameplay/Weapons/ConstantParticleWeaponManager.cs @@ -19,8 +19,7 @@ public class ConstantParticleWeaponManager : ConstantWeaponEffectManager t.SetParent(barrel); t.forward = barrel.forward; t.position = barrel.position; - p.Damage = item.Evaluate(data.Damage); - p.DamageType = data.DamageType; + // Cut 4 (docs/fire-control-cut.md): FireControl already rolls this weapon's damage. _weapons.Add(item, p); p.Initialize(); } diff --git a/Assets/Scripts/Gameplay/Weapons/HitscanEffect.cs b/Assets/Scripts/Gameplay/Weapons/HitscanEffect.cs index 49201cfe0..673e38be6 100644 --- a/Assets/Scripts/Gameplay/Weapons/HitscanEffect.cs +++ b/Assets/Scripts/Gameplay/Weapons/HitscanEffect.cs @@ -1,8 +1,11 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; -using static CultMath.math; +// Cut 4 (docs/fire-control-cut.md): the raycast, shield branch and SendHit are deleted -- FireControl already +// decided this shot's fate before Fire() was ever called (R8), the same as Laser/Lightning (Cut 3). What is +// left is pure endpoint presentation: draw to the target's current position when there is one, out to Range +// otherwise. public class HitscanEffect : MonoBehaviour { public float Duration; @@ -10,71 +13,31 @@ public class HitscanEffect : MonoBehaviour public LineRenderer Line; public ParticleSystem LineEffect; public Prototype HitEffect; - - public Zone Zone { get; set; } - - public float Damage { get; set; } - public float Penetration { get; set; } - public float Spread { get; set; } - public DamageType DamageType { get; set; } + + // Cut 4: FireControl.Fire's ShotId -- unused by this endpoint-only presentation today, kept so a future + // pass can draw to the exact rolled cell instead of the target's overall position (Laser.ShotId). + public int ShotId { get; set; } public Entity SourceEntity { get; set; } public float Range { get; set; } - + public Transform TargetTransform { get; set; } + private float _startTime; private bool _active = false; - + public void Fire() { _startTime = Time.time; - var hitFound = false; - var ray = new Ray(transform.position, transform.forward); - foreach (var hit in Physics.RaycastAll(ray, Range, 1 | (1 << 17))) - { - var shield = hit.collider.GetComponent(); - if (shield) - { - if (!(shield.Entity.Shield != null && shield.Entity.Shield.Item.Active.Value && shield.Entity.Shield.CanTakeHit(DamageType, Damage))) continue; - if (shield.Entity != SourceEntity) - { - shield.Entity.Shield.TakeHit(DamageType, Damage); - shield.ShowHit(hit.point, sqrt(Damage)); - hitFound = true; - } - } - var hull = hit.collider.GetComponent(); - if (hull) - { - if (hull.Entity != SourceEntity) - { - hull.SendHit(Damage, Penetration, Spread, DamageType, SourceEntity, hit.textureCoord, transform.forward); - hitFound = true; - } - } - - if (hitFound && HitEffect != null) - { - var ht = HitEffect.Instantiate(); - ht.SetParent(hit.collider.transform); - ht.position = hit.point; - } - - var length = (hit.point - transform.position).magnitude; - Line.SetPosition(1, Vector3.forward * length); - var emission = LineEffect.emission; - emission.rateOverTimeMultiplier = length; - var shape = LineEffect.shape; - shape.position = Vector3.forward * (length / 2); - shape.scale = Vector3.one * (length / 2); - } - if(!hitFound) - { - Line.SetPosition(1, Vector3.forward * Range); - var emission = LineEffect.emission; - emission.rateOverTimeMultiplier = Range; - var shape = LineEffect.shape; - shape.position = Vector3.forward * (Range / 2); - shape.scale = Vector3.one * (Range / 2); - } + var length = TargetTransform != null + ? Vector3.Distance(transform.position, TargetTransform.position) + : Range; + + Line.SetPosition(1, Vector3.forward * length); + var emission = LineEffect.emission; + emission.rateOverTimeMultiplier = length; + var shape = LineEffect.shape; + shape.position = Vector3.forward * (length / 2); + shape.scale = Vector3.one * (length / 2); + LineEffect.Play(true); _active = true; } diff --git a/Assets/Scripts/Gameplay/Weapons/HitscanManager.cs b/Assets/Scripts/Gameplay/Weapons/HitscanManager.cs index 3c4f8416e..5075c3344 100644 --- a/Assets/Scripts/Gameplay/Weapons/HitscanManager.cs +++ b/Assets/Scripts/Gameplay/Weapons/HitscanManager.cs @@ -15,12 +15,9 @@ public class HitscanManager : InstantWeaponEffectManager t.localPosition = Vector3.zero; // t.position = barrel.position; // t.forward = barrel.forward; + p.ShotId = shotId; p.Range = weapon.Range; - p.Damage = weapon.Damage; - p.Penetration = weapon.Penetration; - p.Spread = weapon.DamageSpread; - p.DamageType = weapon.WeaponData.DamageType; - p.Zone = source.Entity.Zone; + p.TargetTransform = target != null ? target.transform : null; p.Fire(); } } \ No newline at end of file diff --git a/Assets/Scripts/Gameplay/Weapons/Mine.cs b/Assets/Scripts/Gameplay/Weapons/Mine.cs index 3807270d3..db0f82141 100644 --- a/Assets/Scripts/Gameplay/Weapons/Mine.cs +++ b/Assets/Scripts/Gameplay/Weapons/Mine.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using CultMath; +using CultMath.UnityBridge; using static CultMath.math; using UnityEngine; using Random = UnityEngine.Random; @@ -86,35 +87,16 @@ public class Mine : MonoBehaviour _material.SetFloat("_Emission", _emission * EmissionCurve.Evaluate(_pulseLerp)); } + // Cut 4 (docs/fire-control-cut.md, Q7): the arming OverlapSphere above stays -- that is contact detection, + // not hit detection. Blast damage is not: it goes through the same FireControl.Splash every splash-shaped + // weapon uses now, over the zone's own planar entities, not a Unity collider query. Presentation (ShowHit) + // goes with the query it depended on -- nothing here decides who was hit any more, so nothing here can + // point a hit effect at them; a future pass can rebuild that off FireControl-published state if the mine + // ever ships (R9 keeps it regardless). public void Explode() { var position = transform.position; - foreach (var collider in Physics.OverlapSphere(position, BlastRange, 1 | (1 << 17))) - { - var shield = collider.GetComponent(); - if (shield) - { - var shieldBehavior = shield.Entity.Shield; - var shieldActive = shieldBehavior != null && shieldBehavior.Item.Active.Value; - var shieldAbsorbs = shieldActive && shieldBehavior.CanTakeHit(DamageType, Damage); - // F5 (docs/stats-and-power-cut.md, Soul pass 2026-09-19): CanTakeHit is a pure query now -- read - // once into shieldAbsorbs, and break the shield exactly once, right here, at the point this hit - // is actually decided to route past it (to the hull collider OverlapSphere returns as a - // separate entry in this same loop) instead of being absorbed. The hull branch below re-queries - // CanTakeHit safely -- it is side-effect-free -- and will see Broken already true. - if (shieldActive && !shieldAbsorbs) shieldBehavior.Break(); - if (shieldAbsorbs) - { - shieldBehavior.TakeHit(DamageType, Damage); - shield.ShowHit(position, sqrt(Damage)); - } - } - var hull = collider.GetComponent(); - if (hull && !(hull.Entity.Shield != null && hull.Entity.Shield.Item.Active.Value && hull.Entity.Shield.CanTakeHit(DamageType, Damage))) - { - hull.SendSplash(Damage, DamageType, Source.Entity, (collider.transform.position - position).normalized); - } - } + FireControl.Splash(Source.Entity.Zone, position.ToCultMath(), BlastRange, Damage, DamageType); var ht = HitEffect.Instantiate(); ht.position = position; diff --git a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs index 5f7e3293d..1d8fe567f 100644 --- a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs @@ -32,6 +32,9 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC private float _ammoInterval; private float _reload; private bool _reloading; + // Cut 4 (docs/fire-control-cut.md): accumulates while firing; rolled off every time it reaches + // GameplaySettings.BeamResolveInterval, through FireControl.Fire/Step exactly like a discrete shot. + private float _beamTimer; public override int Ammo { @@ -53,13 +56,18 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC public event Action OnReloadComplete; public event Action OnStartFiring; public event Action OnStopFiring; - + // Cut 4 (docs/fire-control-cut.md): carries the ShotId each beam roll's FireControl.Fire assigned, the + // same handle InstantWeapon.OnFire gives discrete shots. No presentation binds to it yet -- kept for a + // future pass, same as Laser.ShotId. + public event Action OnBeamShot; + public void ResetEvents() { OnReloadBegin = null; OnReloadComplete = null; OnStartFiring = null; OnStopFiring = null; + OnBeamShot = null; } public ConstantWeapon(ConstantWeaponData data, EquippedItem item) : base(data, item) @@ -152,6 +160,23 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC CauseWearDamage(dt); AddHeat(Evaluate(_data.Heat) * dt); Entity.VisibilitySources[this] = Evaluate(_data.Visibility); + + // Cut 4 (docs/fire-control-cut.md): a beam is a sequence of rolls, not a continuous truth -- one + // FireControl.Fire per BeamResolveInterval, for that interval's worth of Damage, through the same + // freeze-and-queue path a discrete shot uses (a beam's authored Velocity is 0, so the flight + // commits and resolves in this same tick, R4's short-flight degradation). + var interval = Entity.ItemManager.GameplaySettings.BeamResolveInterval; + _beamTimer += dt; + while (_beamTimer >= interval) + { + _beamTimer -= interval; + // FireControl.Fire must run whether or not anything is listening: `OnBeamShot?.Invoke(FireControl.Fire(...))` + // looks equivalent but is not -- C#'s null-conditional short-circuits the whole expression, + // argument included, when OnBeamShot has no subscriber (true today, R9's "no design uses it + // yet"), so the roll would silently never happen. Evaluate it into a local first. + var shotId = FireControl.Fire(this, Item, Entity, Damage * interval); + OnBeamShot?.Invoke(shotId); + } } return true; } diff --git a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs index f87009974..6b9b14fc8 100644 --- a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs @@ -240,7 +240,13 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo // Cut 3: this is fire authority's one entry point. FireControl.Fire freezes the payload snapshot // (Q6 -- the gun's own stats at this exact instant, base.Execute(dt) above already refreshed them // this tick) and queues a PendingShot; nothing downstream re-evaluates a stat. - OnFire?.Invoke(FireControl.Fire(this, Item, Entity)); + // Cut 4 fix: FireControl.Fire must run whether or not anything is listening -- inlined into + // `OnFire?.Invoke(...)` it looked equivalent but was not. C#'s null-conditional short-circuits the + // whole expression, argument included, whenever OnFire has no subscriber (a headless run with no + // Unity EntityInstance wiring, docs/headless-playground-cut.md), so a shot silently never fired. + // Evaluate it into a local first. + var shotId = FireControl.Fire(this, Item, Entity); + OnFire?.Invoke(shotId); if(!firedThisFrame) { Item.FireAudioEvent(WeaponAudioEvent.Fire); diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 74fc8e358..b49c90105 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -155,7 +155,12 @@ public static class FireControl // flight time, freezes the payload snapshot (R10, Q6 -- the gun that fired it, not a re-read later), and // queues a PendingShot for Zone.Step to age and eventually resolve. Returns the ShotId so the caller's // OnFire event can carry it to presentation. - public static int Fire(Weapon weapon, EquippedItem item, Entity source) + // Cut 4 (docs/fire-control-cut.md): damageOverride lets a continuous weapon fire a shot for less than its + // full Damage -- ConstantWeapon.Execute rolls one of these per GameplaySettings.BeamResolveInterval, for + // Damage * interval, through this exact same freeze-and-queue path (a flight time of zero, since a beam's + // authored Velocity is 0, commits and resolves in the tick it fires -- R4's short-flight degradation, + // unchanged). Every other caller keeps reading the frozen weapon.Damage it always did. + public static int Fire(Weapon weapon, EquippedItem item, Entity source, float? damageOverride = null) { var zone = source.Zone; var target = source.Target.Value; @@ -186,7 +191,7 @@ public static class FireControl Target = target, Weapon = item, Aimed = source.ResolvedTargetItem, - Damage = weapon.Damage, + Damage = damageOverride ?? weapon.Damage, Penetration = weapon.Penetration, DamageSpread = weapon.DamageSpread, DamageType = weapon.WeaponData.DamageType, @@ -337,6 +342,49 @@ public static class FireControl }; } + // Cut 4 (docs/fire-control-cut.md): the one splash rule -- an unconditional area effect, not a rolled + // shot. Nothing here draws: a mine or an airburst round always damages everything it catches, the same + // as the Physics.OverlapSphere queries this replaces always did. Applies the shield-absorb-or-hull-takes- + // it branch (F5, docs/stats-and-power-cut.md) per target, then -- for a target the shield didn't fully + // absorb -- DamageSchematic over the directional half of that target's own hull that faces the blast, the + // rule moved verbatim from the Splash subscription EntityInstance.cs carried before Cut 3 deleted it + // (git show b7743789^:Assets/Scripts/Gameplay/EntityInstance.cs), made planar (R7): the blast-to-target + // direction is measured in the zone's (x,z) plane and rotated into each target's own facing by its + // Direction, the same rotation Entity.ApplyHit's penetration march uses, in place of a Unity + // InverseTransformDirection. + public static void Splash(Zone zone, float3 position, float radius, float damage, DamageType damageType) + { + foreach (var target in zone.Entities) + { + var toTarget = (target.Position - position).xz; + if (length(toTarget) > radius) continue; + + var shield = target.Shield; + var shieldActive = shield != null && shield.Item.Active.Value; + var shieldAbsorbs = shieldActive && shield.CanTakeHit(damageType, damage); + if (shieldActive && !shieldAbsorbs) shield.Break(); + if (shieldAbsorbs) + { + shield.TakeHit(damageType, damage); + continue; + } + + var hullData = target.ItemManager.GetData(target.Hull) as HullData; + var forward = normalize(target.Direction); + var right = float2(forward.y, -forward.x); + var localDirection = lengthsq(toTarget) > 1e-6f + ? normalize(float2(dot(toTarget, right), dot(toTarget, forward))) + : float2(0, 1); + + var hitShape = new Shape(hullData.Shape.Width, hullData.Shape.Height); + foreach (var v in hullData.Shape.Coordinates) + if (dot(normalize((float2) v - hullData.Shape.CenterOfMass), localDirection) < 0) + hitShape[v] = true; + + target.DamageSchematic(damage, hitShape); + } + } + // The cells of the target's hull schematic actually occupied by `item` -- GearOccupancy is the one source // of truth for where an equipped item's footprint lands, the same table Entity.DamageSchematic reads. private static int2[] CellsOf(Entity target, EquippedItem item) diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 1cfcb53a1..35c53693f 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -240,6 +240,12 @@ public class GameplaySettings // a firing solution worth taking (Combat.cs, TurretController.cs). Player fire is gated on arc alone // (Weapon.ArcAllowsFire, Q2) -- this threshold is an AI fire-discipline heuristic, not part of the roll. public float AgentMinHitProbability = .2f; + + // Cut 4 (docs/fire-control-cut.md): how often a continuous weapon (ConstantWeapon) rolls a discrete + // outcome for Damage * this interval, through the same FireControl.Fire/Step pair a discrete shot uses -- + // a beam is a sequence of rolls, not a continuous truth. First guess; the headless fixture is the tuning + // harness, the operator smoke is the arbiter, same as Cut 3's other first guesses. + public float BeamResolveInterval = .25f; } [Serializable, MessagePackObject(keyAsPropertyName: true), JsonObject] diff --git a/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs b/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs new file mode 100644 index 000000000..cc30e415c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs @@ -0,0 +1,329 @@ +/* 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 float2 = CultMath.float2; +using float3 = CultMath.float3; +using int2 = CultMath.int2; + +// Cut 4 (docs/fire-control-cut.md): pins the two rules this cut actually adds -- a continuous weapon is a +// sequence of rolls rather than a continuous truth, and splash (mine/airburst blast) is one rule applied to +// every entity in radius, directional over each target's own hull. FireAuthorityTests.cs already pins the +// roll itself (seeding, commit horizon, the shield-absorb branch, the damage rule); this file builds its own +// minimal fixtures rather than reusing that one's InstantWeapon-shaped Engagement, the same convention that +// file's own comment establishes. +public sealed class FireControlCut4Tests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolcut4-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public FireControlCut4Tests() => 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, + FiringArc = 170, + CommitHorizon = .5f, + SchematicCellSize = 1f, + UnaidedAccuracy = .05f, + AgentMinHitProbability = 0f, + BeamResolveInterval = .1f + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + // A 5x5 fully-solid hull, the same shape FireAuthorityTests.Build uses. + private static HullData MakeHullData(float armor = 0) => new HullData + { + Name = "Hull", HullType = HullType.Ship, Shape = SolidShape(), Durability = 1000, Mass = 1000, Armor = armor, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }; + + private static Shape SolidShape() + { + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // ---- Cut 4's beam rule: ConstantWeapon rolls once per BeamResolveInterval, not once per tick and not + // once for the whole burst. ---- + + private sealed class BeamEngagement + { + public ItemManager Items; + public Zone Zone; + public Ship Shooter; + public Ship Target; + public ConstantWeapon Weapon; + } + + private BeamEngagement BuildBeam(GameplaySettings settings, float damage, float targetRange = 100) + { + var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); + _openCaches.Add(cache); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(MakeHullData()); + cache.Upsert(new GearData + { + Name = "Beam", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new ConstantWeaponData + { + Damage = Constant(damage), Range = Constant(1000), MinRange = Constant(0), + Velocity = Constant(0), Spread = Constant(0), DamageSpread = Constant(0), Penetration = Constant(0), + 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(1), Resolution = Constant(1), Precision = Constant(0), Tracking = Constant(1000) + } } + }); + // Powers the beam: with no Reactor, PowerBus grants nothing and ConstantWeapon.Execute safes itself + // off (Item.PowerSupply <= 1e-4f) after the first tick, same rake FireAuthorityTests.ShieldTakesHit + // notes for its own Reactor/Shield pair. + cache.Upsert(new GearData + { + Name = "Reactor", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new ReactorData { Charge = Constant(1000), Efficiency = Constant(1), OverloadEfficiency = Constant(1), ThrottlingFactor = Constant(2) } } + }); + 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 }; + ledger.Lots[9] = 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 = 1000, Lot = 1 }; + var shooter = new Ship(items, zone, shooterHull, new EntitySettings()); + + var gunRef = items.ItemData.RefOf(items.ItemData.GetByName("Beam")); + 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 = (ConstantWeapon) 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 reactorRef = items.ItemData.RefOf(items.ItemData.GetByName("Reactor")); + var reactor = new EquippableItem { Data = reactorRef, Durability = 10, Lot = 5 }; + Assert.True(shooter.TryFindSpace(reactor, out var rpos)); + Assert.True(shooter.TryEquip(reactor, rpos)); + + var targetHull = new EquippableItem { Data = hullRef, Durability = 1000, Lot = 4 }; + var target = new Ship(items, zone, targetHull, new EntitySettings()); + var targetGunRef = items.ItemData.RefOf(items.ItemData.GetByName("Beam")); + var targetGun = new EquippableItem { Data = targetGunRef, Durability = 1, Lot = 9 }; + 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, same as FireAuthorityTests.Build + + return new BeamEngagement { Items = items, Zone = zone, Shooter = shooter, Target = target, Weapon = weapon }; + } + + // A beam is a sequence of discrete rolls, not a continuous truth: over one second it produces exactly + // 1/BeamResolveInterval outcomes, each for Damage*BeamResolveInterval, totalling Damage. Interval (.25s) + // and tick (.125s) are both exact dyadic fractions so float accumulation cannot drift the count -- and the + // tick is strictly smaller than the interval, so the two are distinguishable from a "one roll per tick" + // mutant (which would produce 8 outcomes here, not 4) and from a "one roll per burst" mutant (1, not 4). + [Fact] + public void BeamRollsPerInterval() + { + var settings = TestSettings(); + settings.BeamResolveInterval = .25f; + var e = BuildBeam(settings, damage: 10); + + var outcomes = new List(); + e.Zone.ShotResolved.Subscribe(outcome => { outcomes.Add(outcome); }); + + e.Weapon.Activate(); + for (var i = 0; i < 8; i++) e.Zone.Update(.125f); // 1 second in 8 ticks of .125s + + Assert.Equal(4, outcomes.Count); // 1s / .25s per roll + Assert.All(outcomes, o => Assert.True(o.Hit)); + Assert.Equal(10f, outcomes.Count * 10f * settings.BeamResolveInterval, 2); // Damage * interval, per roll + } + + // ---- Regression: FireControl.Fire must run whether or not a presentation is listening. Both + // InstantWeapon.Execute and ConstantWeapon.Execute used to write `OnFire?.Invoke(FireControl.Fire(...))` + // inline -- C#'s null-conditional short-circuits the WHOLE expression, argument included, whenever the + // event has no subscriber, so with no Unity EntityInstance wired up (a headless run, + // docs/headless-playground-cut.md) the shot silently never fired. Caught by this cut's own + // BeamRollsPerInterval fixture; this test pins the discrete-weapon half of the same fix, which no + // existing test could catch because FireAuthorityTests.cs always calls FireControl.Fire directly, never + // through Trigger()/Execute(). Mutation: inline the call back into the null-conditional. ---- + [Fact] + public void InstantWeaponFiresWithoutAnyOnFireSubscriber() + { + var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); + _openCaches.Add(cache); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(MakeHullData()); + cache.Upsert(new GearData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new InstantWeaponData + { + Damage = Constant(10), Range = Constant(1000), MinRange = Constant(0), Velocity = Constant(0), + Spread = Constant(0), 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.FlushAsync().Wait(); + + var ledger = new ProvenanceLedger { Lots = { [1] = new Lot { Origin = new Attributed(), Quality = 1 } } }; + var items = new ItemManager(cache, ledger, TestSettings(), _ => { }); + 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 = 1000, 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 = 1 }; + Assert.True(shooter.TryEquip(gun, new int2(0, 0))); + var weapon = (InstantWeapon) shooter.Equipment.Single(e => e.EquippableItem == gun).Behaviors.Single(b => b is Weapon); + + zone.Entities.Add(shooter); + shooter.Activate(); + zone.Update(0f); // warm up resolved stats + + // No target, no OnFire subscriber -- exactly a headless shooter with no target and no presentation. + var resolvedCount = 0; + zone.ShotResolved.Subscribe(_ => resolvedCount++); + + weapon.Activate(); // Trigger() -> queues a burst + zone.Update(.016f); // one ordinary tick -- Execute() should fire and the zero-velocity shot resolves same tick + + Assert.Equal(1, resolvedCount); + } + + // ---- Cut 4's splash rule: FireControl.Splash is an unconditional area effect (no roll), directional per + // target's own hull facing. Tested directly against the function, no weapon/gear catalog needed -- Entity. + // MapEntity (called from the Entity constructor) is enough to give a Ship its Armor/GearOccupancy/Hull. ---- + + private ProvenanceLedger _splashLedger; + + private (ItemManager Items, Zone Zone) BuildSplashZone(GameplaySettings settings, float armor = 0) + { + var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); + _openCaches.Add(cache); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(MakeHullData(armor)); + cache.FlushAsync().Wait(); + + _splashLedger = new ProvenanceLedger(); + var items = new ItemManager(cache, _splashLedger, settings, _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + return (items, zone); + } + + private Ship AddShip(ItemManager items, Zone zone, float3 position, float2 direction, int lot) + { + _splashLedger.Lots[lot] = new Lot { Origin = new Attributed(), Quality = 1 }; + var hullRef = items.ItemData.RefOf(items.ItemData.GetByName("Hull")); + var hull = new EquippableItem { Data = hullRef, Durability = 1000, Lot = lot }; + var ship = new Ship(items, zone, hull, new EntitySettings()); + ship.Position = position; + ship.Direction = direction; + zone.Entities.Add(ship); + return ship; + } + + // Splash is one rule, not per-effect: every entity within radius takes damage, one outside radius takes + // none. Mutation: damage only the nearest entity in range instead of every one. + [Fact] + public void SplashHitsEveryEntityInRadius() + { + var (items, zone) = BuildSplashZone(TestSettings()); + var near = AddShip(items, zone, float3(10, 0, 0), float2(0, 1), 1); + var far = AddShip(items, zone, float3(20, 0, 0), float2(0, 1), 2); + var outOfRange = AddShip(items, zone, float3(1000, 0, 0), float2(0, 1), 3); + + var nearBefore = near.Hull.Durability; + var farBefore = far.Hull.Durability; + var outBefore = outOfRange.Hull.Durability; + + FireControl.Splash(zone, float3.zero, radius: 30, damage: 50, damageType: DamageType.Kinetic); + + Assert.True(near.Hull.Durability < nearBefore); + Assert.True(far.Hull.Durability < farBefore); + Assert.Equal(outBefore, outOfRange.Hull.Durability); + } + + // Splash is directional over each target's own hull: cells facing the blast take it, cells facing away do + // not. Mutation: damage the whole shape regardless of direction. + [Fact] + public void SplashIsDirectional() + { + // Nonzero armor so an undamaged cell is distinguishable from a damaged one -- with armor 0 every cell + // starts and stays at 0 regardless of which half took the schematic hit. + var (items, zone) = BuildSplashZone(TestSettings(), armor: 10); + // Facing +Z (the default); the blast sits behind the ship along -Z, so the near half of the hull + // (negative-Z cells, closest to the blast) should take damage and the far half (positive-Z) should not. + var ship = AddShip(items, zone, float3(0, 0, 10), float2(0, 1), 1); + + FireControl.Splash(zone, float3(0, 0, 0), radius: 50, damage: 1000, damageType: DamageType.Kinetic); + + var hullData = (HullData) items.GetData(ship.Hull); + var center = hullData.Shape.CenterOfMass; + var nearCellDamaged = false; + var farCellUntouched = false; + foreach (var v in hullData.Shape.Coordinates) + { + var offset = (float2) v - center; + if (offset.y < -.5f && ship.Armor[v.x, v.y] < ship.MaxArmor[v.x, v.y]) nearCellDamaged = true; + if (offset.y > .5f && ship.Armor[v.x, v.y] >= ship.MaxArmor[v.x, v.y]) farCellUntouched = true; + } + + Assert.True(nearCellDamaged); + Assert.True(farCellUntouched); + } +} diff --git a/tests/mutation_tests_fire_control_cut4.py b/tests/mutation_tests_fire_control_cut4.py new file mode 100644 index 000000000..87fb19e22 --- /dev/null +++ b/tests/mutation_tests_fire_control_cut4.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Mutation tests for docs/fire-control-cut.md's Cut 4 ("The unused kinds join the same path") -- the last five +weapon kinds (ConstantLaser, ConstantLightning, ConstantParticleWeapon, HitscanEffect, Mine) stop deciding +their own hits through live Physics queries and join FireControl, the same owner Cut 3 gave the other four. + +Four rules are pinned here, each against tests/Aetheria.Shared.Tests/FireControlCut4Tests.cs: + + 1. BeamRollsPerInterval: a continuous weapon (ConstantWeapon) is a sequence of discrete rolls, one per + GameplaySettings.BeamResolveInterval, not a roll per tick and not one roll for the whole burst. + 2. InstantWeaponFiresWithoutAnyOnFireSubscriber / (implicitly) BeamRollsPerInterval again: FireControl.Fire + must run whether or not a presentation is listening -- a real Cut 3/4 defect this campaign found and + fixed. Inlining the call back into `OnFire?.Invoke(FireControl.Fire(...))` silently stops every shot from + firing in a headless run (no Unity EntityInstance ever subscribes OnFire/OnBeamShot), because C#'s + null-conditional short-circuits the whole expression, argument included, when the event has no + subscriber. Pinned on both InstantWeapon.cs and ConstantWeapon.cs since Cut 3 introduced the pattern once + and Cut 4 copied it a second time. + 3. SplashHitsEveryEntityInRadius: FireControl.Splash (mine/airburst blast) is one rule applied to every + entity within radius, not just the nearest. + 4. SplashIsDirectional: splash damage lands on the half of each target's own hull that faces the blast, not + the whole hull. + +A no-op control mutation proves the read/replace/restore path is transparent. + +Usage: + python tests/mutation_tests_fire_control_cut4.py --cultlib-root + +Only touches files under this repository; every mutation is reversed before the script exits, including on +failure. +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +TEST_PROJECT = REPO_ROOT / "tests" / "Aetheria.Shared.Tests" +CONSTANT_WEAPON_CS = "Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs" +INSTANT_WEAPON_CS = "Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs" +FIRE_CONTROL_CS = "Assets/Scripts/ServerShared/FireControl.cs" + + +@dataclass +class Mutation: + rule: str + file: str + anchor: str + mutated: str + test: str + expect: str # "red" (mutant must be killed) or "green" (the no-op control) + + +MUTATIONS: list[Mutation] = [ + # --- No-op control: proves the anchor/replace/restore mechanism is transparent --- + Mutation( + rule="control (no-op round trip)", + file=CONSTANT_WEAPON_CS, + anchor=" while (_beamTimer >= interval)", + mutated=" while (_beamTimer >= interval)", + test="FireControlCut4Tests.BeamRollsPerInterval", + expect="green", + ), + + # --- A beam is a sequence of rolls, not a continuous truth: roll per tick (many more, much smaller + # --- outcomes over the same second) must be killed. --- + Mutation( + rule="ConstantWeapon must roll once per BeamResolveInterval, not once per tick", + file=CONSTANT_WEAPON_CS, + anchor=" while (_beamTimer >= interval)", + mutated=" while (true)", + test="FireControlCut4Tests.BeamRollsPerInterval", + expect="red", + ), + + # --- The opposite direction: rolling once for the whole burst (never draining the timer back below + # --- interval) must also be killed -- a single outcome instead of a sequence. --- + Mutation( + rule="ConstantWeapon must not roll once for the whole burst", + file=CONSTANT_WEAPON_CS, + anchor=" _beamTimer -= interval;", + mutated=" _beamTimer = float.NegativeInfinity;", + test="FireControlCut4Tests.BeamRollsPerInterval", + expect="red", + ), + + # --- The real defect this campaign found: FireControl.Fire must run whether or not OnBeamShot has a + # --- subscriber. Inlining it back into the null-conditional silently stops every beam from firing in a + # --- headless run (nothing ever subscribes OnBeamShot). --- + Mutation( + rule="ConstantWeapon.Execute must evaluate FireControl.Fire even with no OnBeamShot subscriber", + file=CONSTANT_WEAPON_CS, + anchor=" var shotId = FireControl.Fire(this, Item, Entity, Damage * interval);\n OnBeamShot?.Invoke(shotId);", + mutated=" OnBeamShot?.Invoke(FireControl.Fire(this, Item, Entity, Damage * interval));", + test="FireControlCut4Tests.BeamRollsPerInterval", + expect="red", + ), + + # --- The same defect, in InstantWeapon.cs (Cut 3's original copy of the pattern) -- caught only by this + # --- cut's own regression test, since FireAuthorityTests.cs always calls FireControl.Fire directly and + # --- never exercises Trigger()/Execute() with zero OnFire subscribers. --- + Mutation( + rule="InstantWeapon.Execute must evaluate FireControl.Fire even with no OnFire subscriber", + file=INSTANT_WEAPON_CS, + anchor=" var shotId = FireControl.Fire(this, Item, Entity);\n OnFire?.Invoke(shotId);", + mutated=" OnFire?.Invoke(FireControl.Fire(this, Item, Entity));", + test="FireControlCut4Tests.InstantWeaponFiresWithoutAnyOnFireSubscriber", + expect="red", + ), + + # --- Splash is one rule, not per-effect: damaging only the nearest entity in range instead of every one + # --- must be killed. --- + Mutation( + rule="FireControl.Splash must damage every entity in radius, not only the nearest", + file=FIRE_CONTROL_CS, + anchor=" var toTarget = (target.Position - position).xz;\n if (length(toTarget) > radius) continue;", + mutated=" var toTarget = (target.Position - position).xz;\n if (length(toTarget) > radius) continue;\n if (zone.Entities.Where(e => length((e.Position - position).xz) <= radius).OrderBy(e => length((e.Position - position).xz)).First() != target) continue;", + test="FireControlCut4Tests.SplashHitsEveryEntityInRadius", + expect="red", + ), + + # --- Splash is directional over each target's own hull: damaging the whole shape regardless of facing + # --- must be killed. --- + Mutation( + rule="FireControl.Splash must damage only the half of the hull facing the blast, not the whole shape", + file=FIRE_CONTROL_CS, + anchor=" if (dot(normalize((float2) v - hullData.Shape.CenterOfMass), localDirection) < 0)\n hitShape[v] = true;", + mutated=" hitShape[v] = true;", + test="FireControlCut4Tests.SplashIsDirectional", + expect="red", + ), +] + + +def replace_unique(path: Path, anchor: str, mutated: str) -> None: + original = path.read_text(encoding="utf-8") + count = original.count(anchor) + if count != 1: + raise SystemExit(f"{path}: anchor must occur exactly once, found {count}\n---\n{anchor}") + path.write_text(original.replace(anchor, mutated), encoding="utf-8") + + +def run_test(cultlib_root: str, test: str) -> tuple[int, str]: + proc = subprocess.run( + ["dotnet", "test", str(TEST_PROJECT), f"-p:CultLibRoot={cultlib_root}", + "--filter", f"FullyQualifiedName~{test}"], + capture_output=True, text=True, timeout=300, + ) + return proc.returncode, proc.stdout + proc.stderr + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--cultlib-root", required=True) + args = parser.parse_args() + + failures: list[str] = [] + originals: dict[str, str] = {} + for m in MUTATIONS: + if m.file not in originals: + originals[m.file] = (REPO_ROOT / m.file).read_text(encoding="utf-8") + + def restore_all() -> None: + for file, text in originals.items(): + (REPO_ROOT / file).write_text(text, encoding="utf-8") + + try: + for m in MUTATIONS: + print(f"\n=== {m.rule} (expect {m.expect}) ===") + path = REPO_ROOT / m.file + replace_unique(path, m.anchor, m.mutated) + code, output = run_test(args.cultlib_root, m.test) + passed = "Passed!" in output and code == 0 + if m.expect == "green": + if not passed: + failures.append(f"{m.rule}: expected green (test passing), got failure\n{output[-2000:]}") + else: + print(f"OK: {m.test} passed under a no-op mutation, as expected") + else: + if passed: + failures.append(f"{m.rule}: expected red (mutant killed), but {m.test} still passed") + else: + print(f"OK: {m.test} went red under the mutation, as expected") + # Restore this file immediately so the next mutation starts from a clean tree. + path.write_text(originals[m.file], encoding="utf-8") + finally: + restore_all() + + if failures: + print("\n=== FAILURES ===") + for f in failures: + print(f"- {f}") + return 1 + + print("\nAll mutations behaved as declared.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())