Cut 4: input capacitors close the last direct capacitor spend
Deletes Entity.CanSpendCapacitorCharge/TrySpendCapacitorCharge (and the now-dead _capacitors bookkeeping list that only fed them) -- Cut 3's named, temporary exception for the four instant draws. InstantWeapon (both fire sites), Sensor.Ping, and Shield.CanTakeHit/TakeHit now spend from their own InputCapacitor, filled continuously by PowerBus like every other IPowerConsumer instead of touching the entity's shared bus capacitors directly. InputCapacitor's Capacity/Rate derive from the owning item's Energy and Cooldown, with an authored-override hook (ChargedWeapon repurposes its previously-unused ChargeEnergy stat as that override, per the map's own instruction, rather than adding a new field). A weapon/sensor fire attempt only ever spends exactly Capacity, so it only ever succeeds at full charge -- no fractional shot. Shield is the map's named exception: its reserve is continuous, not an activation buffer, so it allows a partial draw; its size (no Energy/Cooldown pair exists on Shield) is a flagged judgment call, not a spec'd formula. Adds InputCapacitorTests.cs (8 tests) and mutation_tests_stats_power_cut4.py (7 mutations, all behave as declared); removes the one PowerBusTests.cs test and Cut 3 mutation case that exercised the now-deleted Entity methods. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
fc80c8944b
commit
8dacabb3d8
12 changed files with 677 additions and 90 deletions
|
|
@ -67,6 +67,13 @@ public class ChargedWeapon : InstantWeapon
|
|||
public float ChargeTime { get; protected set; }
|
||||
public float ChargeEnergy { get; protected set; }
|
||||
public float ChargeHeat { get; protected set; }
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): "its charge cycle already is a buffer, and ChargeEnergy
|
||||
// should become the fill rate rather than a separate concept." ChargeEnergy was authored but never spent
|
||||
// by anything (Trigger() always paid the base Weapon.Energy per shot); it becomes this weapon's input
|
||||
// capacitor rate instead of the InstantWeapon default (Capacity / Cooldown), so a charged weapon's own
|
||||
// authored charge-up speed IS its sustained rate of fire, not a second, disconnected number.
|
||||
protected override float RateOverride => Evaluate(_data.ChargeEnergy);
|
||||
|
||||
public override float DamagePerSecond => Damage * _data.ChargeFiringDamageMultiplier / (Cooldown + ChargeTime);
|
||||
public override float RangeDamagePerSecond(float range)
|
||||
|
|
|
|||
59
Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs
Normal file
59
Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
/* 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 static CultMath.math;
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md §1.2, §0b "An input capacitor"): the input-only buffer that lets an
|
||||
// instant activation (a shot, a ping, a shield's damage reserve) draw from the PowerBus continuously instead
|
||||
// of spending stored charge directly -- closing Cut 3's named, temporary exception
|
||||
// (Entity.TrySpendCapacitorCharge/CanSpendCapacitorCharge, both deleted with their last caller this cut).
|
||||
//
|
||||
// Not a Behavior of its own: per §0b, an input capacitor is identified by the Behavior instance that owns it
|
||||
// (InstantWeapon, Sensor, Shield), which holds one of these as a plain field. Two writers, disjoint signs,
|
||||
// named: the bus fills it, through AddCharge, called only from the owning behaviour's own Execute after it
|
||||
// reads back its granted fraction from Item.PowerSupply; the owning behaviour drains it, through TrySpend,
|
||||
// called only when it actually activates. Nothing else may touch Charge.
|
||||
public class InputCapacitor
|
||||
{
|
||||
public float Capacity { get; private set; }
|
||||
public float Rate { get; private set; }
|
||||
public float Charge { get; private set; }
|
||||
|
||||
// Cut 4 (§7 Q4, operator ruling): "derived from the item's Energy and Cooldown ... with an authored
|
||||
// override" so burst capacity and sustained rate stay separate levers. capacityOverride/rateOverride of 0
|
||||
// mean "not authored, use the derived default" -- the same identity-when-absent convention PerformanceStat
|
||||
// itself already uses (a term-less stat resolves to its identity factor). Cutting Charge down here (rather
|
||||
// than only clamping in AddCharge) is what lets a Capacity that shrinks under a stat change immediately
|
||||
// stop promising a shot it can no longer pay for.
|
||||
public void UpdateStats(float energy, float cooldown, float capacityOverride = 0f, float rateOverride = 0f)
|
||||
{
|
||||
Capacity = capacityOverride > 0f ? capacityOverride : max(0f, energy);
|
||||
Rate = rateOverride > 0f ? rateOverride : (cooldown > 0f ? Capacity / cooldown : Capacity);
|
||||
Charge = clamp(Charge, 0f, Capacity);
|
||||
}
|
||||
|
||||
// What PowerBus should count as this consumer's demand this tick (via the owning behaviour's
|
||||
// IPowerConsumer.PowerRequest), and what that behaviour should scale by its own Item.PowerSupply and pass
|
||||
// to AddCharge once its own Execute runs. The two calls must agree on dt and must not have let Charge move
|
||||
// in between, because PowerBus.Step calls this before any behaviour's Execute runs this tick (§1.2:
|
||||
// "computable from state that is already current at that point").
|
||||
public float RequestedFill(float dt) => min(Rate * dt, max(0f, Capacity - Charge));
|
||||
|
||||
public void AddCharge(float amount) => Charge = clamp(Charge + amount, 0f, Capacity);
|
||||
|
||||
public bool CanSpend(float cost) => Charge >= cost;
|
||||
|
||||
// Atomic and whole-or-nothing, mirroring Entity.TrySpendCapacitorCharge's old contract exactly (down to the
|
||||
// near-zero shortcut) but scoped to this one behaviour's own buffer instead of the entity's shared bus
|
||||
// capacitors: either the cost is covered in full, or nothing moves. This is the mechanism behind the
|
||||
// operator's ruling that no item ever receives a fraction of a shot -- callers that want that guarantee
|
||||
// spend exactly Capacity, which only ever succeeds at full charge.
|
||||
public bool TrySpend(float cost)
|
||||
{
|
||||
if (cost < .01f) return true;
|
||||
if (!CanSpend(cost)) return false;
|
||||
Charge -= cost;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 2323335634942be0e17abf63f5c6d256
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -32,10 +32,14 @@ public class InstantWeaponData : WeaponData
|
|||
}
|
||||
}
|
||||
|
||||
public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
|
||||
public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerConsumer
|
||||
{
|
||||
private InstantWeaponData _data;
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): replaces the direct Entity.TrySpendCapacitorCharge spend at
|
||||
// both Trigger() and Execute() below -- the named, temporary exception Cut 3 left standing.
|
||||
protected readonly InputCapacitor _capacitor = new InputCapacitor();
|
||||
|
||||
protected int _burstRemaining;
|
||||
private float _burstTimer;
|
||||
private float _burstInterval;
|
||||
|
|
@ -95,10 +99,7 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
|
|||
|
||||
// If 1 ammo is consumed per burst, perform ammo and energy consumption here
|
||||
// UseAmmo returns false when triggering reload; cancel firing if that is the case
|
||||
// Cut 3 (docs/stats-and-power-cut.md): one of the four instant draws out of scope for the bus this cut
|
||||
// (a burst) -- named, temporary exception, spending capacitor charge directly. Cut 4's input capacitor
|
||||
// closes this.
|
||||
if(_data.SingleAmmoBurst && (!Entity.TrySpendCapacitorCharge(Energy) || !UseAmmo())) return;
|
||||
if(_data.SingleAmmoBurst && (!TrySpendActivationEnergy() || !UseAmmo())) return;
|
||||
|
||||
_burstRemaining = (int) BurstCount;
|
||||
_burstInterval = BurstTime / _burstRemaining;
|
||||
|
|
@ -119,6 +120,36 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
|
|||
Energy /= (int) BurstCount;
|
||||
}
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md §7 Q4): capacity and rate, resolved fresh rather than off the cached
|
||||
// Energy/Cooldown properties above -- Capacitor.ResolveCapacity's precedent (PowerBus.Step, which calls
|
||||
// PowerRequest below, runs before this behaviour's own Execute this tick, so those cached properties would
|
||||
// still hold last tick's value). Capacity is one shot's own energy cost, exactly what the two deleted
|
||||
// direct-spend call sites measured. Default rate keeps sustained fire exactly at Cooldown's pace when the
|
||||
// bus grants the full request; RateOverride lets an owner replace that (ChargedWeapon does).
|
||||
protected virtual float RateOverride => 0f;
|
||||
|
||||
protected void RefreshInputCapacitor()
|
||||
{
|
||||
var burstCount = max(1, (int) Evaluate(_data.Count));
|
||||
var perShotEnergy = Evaluate(_data.Energy) / burstCount;
|
||||
var cooldown = Evaluate(_data.Cooldown);
|
||||
_capacitor.UpdateStats(perShotEnergy, cooldown, rateOverride: RateOverride);
|
||||
}
|
||||
|
||||
// Cut 4: the request PowerBus needs before Execute runs, mirroring EnergyDraw's IPowerConsumer pattern.
|
||||
public float PowerRequest(float dt)
|
||||
{
|
||||
RefreshInputCapacitor();
|
||||
return _capacitor.RequestedFill(dt);
|
||||
}
|
||||
|
||||
// Cut 4: whole-or-nothing against this behaviour's own input capacitor -- the operator's ruling ("no item
|
||||
// ever receives a fraction of a shot") means a fire attempt only ever succeeds at full charge, so the cost
|
||||
// spent is always exactly Capacity, never the possibly-stale cached Energy. A consumable-hosted instance
|
||||
// (Item == null) has no PowerBus entry (Behaviors.cs: "no PowerBus entry ... always succeeds"), so nothing
|
||||
// would ever fill this capacitor -- bypass it entirely rather than starving such an instance forever.
|
||||
protected bool TrySpendActivationEnergy() => Item == null || _capacitor.TrySpend(_capacitor.Capacity);
|
||||
|
||||
private bool UseAmmo()
|
||||
{
|
||||
if (_data.MagazineSize <= 1) return true;
|
||||
|
|
@ -156,6 +187,10 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
|
|||
public override bool Execute(float dt)
|
||||
{
|
||||
base.Execute(dt);
|
||||
// Cut 4: this tick's grant, read back via Item.PowerSupply -- Item is non-null here because a null-Item
|
||||
// instance never reaches PowerBus.Step (see TrySpendActivationEnergy) and so never accrues charge.
|
||||
if (Item != null)
|
||||
_capacitor.AddCharge(_capacitor.RequestedFill(dt) * Item.PowerSupply);
|
||||
if (_coolingDown)
|
||||
{
|
||||
_cooldown -= dt / (_data.MagazineSize > 0 && _ammo == 0 ? _data.ReloadTime : Cooldown);
|
||||
|
|
@ -178,9 +213,7 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
|
|||
{
|
||||
// If multiple ammo is consumed per burst, perform ammo and energy consumption here
|
||||
// UseAmmo returns false when triggering reload; cancel firing if that is the case
|
||||
// Cut 3 (docs/stats-and-power-cut.md): one of the four instant draws out of scope this cut (a shot);
|
||||
// see Trigger()'s SingleAmmoBurst branch above for the same named exception.
|
||||
if (!_data.SingleAmmoBurst && (!Entity.TrySpendCapacitorCharge(Energy) || !UseAmmo()))
|
||||
if (!_data.SingleAmmoBurst && (!TrySpendActivationEnergy() || !UseAmmo()))
|
||||
{
|
||||
_burstRemaining = 0;
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -50,9 +50,13 @@ public class SensorData : BehaviorData
|
|||
}
|
||||
}
|
||||
|
||||
public class Sensor : Behavior, IEventBehavior
|
||||
public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
||||
{
|
||||
private SensorData _data;
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): replaces the direct Entity.TrySpendCapacitorCharge spend in
|
||||
// Ping() below -- the named, temporary exception Cut 3 left standing.
|
||||
private readonly InputCapacitor _capacitor = new InputCapacitor();
|
||||
private float _pingCooldown;
|
||||
private float _pingLerp;
|
||||
private bool _pinging;
|
||||
|
|
@ -80,11 +84,28 @@ public class Sensor : Behavior, IEventBehavior
|
|||
OnPingEnd = null;
|
||||
}
|
||||
|
||||
// Cut 3 (docs/stats-and-power-cut.md): one of the four instant draws out of scope for the bus this cut (a
|
||||
// ping) -- named, temporary exception, spending capacitor charge directly. Cut 4 closes this.
|
||||
// Cut 4: capacity/rate, resolved fresh (Capacitor.ResolveCapacity's precedent -- PowerBus.Step calls
|
||||
// PowerRequest below before this behaviour's own Execute runs this tick).
|
||||
private void RefreshInputCapacitor()
|
||||
{
|
||||
var energy = Evaluate(_data.PingEnergy);
|
||||
var cooldown = Evaluate(_data.PingCooldown);
|
||||
_capacitor.UpdateStats(energy, cooldown);
|
||||
}
|
||||
|
||||
// Cut 4: the request PowerBus needs before Execute runs.
|
||||
public float PowerRequest(float dt)
|
||||
{
|
||||
RefreshInputCapacitor();
|
||||
return _capacitor.RequestedFill(dt);
|
||||
}
|
||||
|
||||
public void Ping()
|
||||
{
|
||||
if(_pingCooldown < 0 && Entity.TrySpendCapacitorCharge(Evaluate(_data.PingEnergy)))
|
||||
// Whole-or-nothing against the ping's own input capacitor -- fires only at full charge (operator
|
||||
// ruling: no fraction of a shot). A consumable-hosted instance (Item == null) has no PowerBus entry, so
|
||||
// nothing would ever fill this capacitor; bypass it rather than starving such an instance forever.
|
||||
if(_pingCooldown < 0 && (Item == null || _capacitor.TrySpend(_capacitor.Capacity)))
|
||||
{
|
||||
Entity.VisibilitySources[this] = Evaluate(_data.PingVisibility);
|
||||
_pinging = true;
|
||||
|
|
@ -108,6 +129,10 @@ public class Sensor : Behavior, IEventBehavior
|
|||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
// Cut 4: this tick's grant, read back via Item.PowerSupply -- Item is non-null here because a null-Item
|
||||
// instance never reaches PowerBus.Step (see Ping()) and so never accrues charge.
|
||||
if (Item != null)
|
||||
_capacitor.AddCharge(_capacitor.RequestedFill(dt) * Item.PowerSupply);
|
||||
if (_pinging)
|
||||
{
|
||||
_pingLerp += dt / _data.PingDuration;
|
||||
|
|
|
|||
|
|
@ -26,13 +26,24 @@ public class ShieldData : BehaviorData
|
|||
}
|
||||
}
|
||||
|
||||
public class Shield : Behavior, IProgressBehavior
|
||||
public class Shield : Behavior, IProgressBehavior, IPowerConsumer
|
||||
{
|
||||
public float Efficiency { get; private set; }
|
||||
public float EnergyUsage { get; private set; }
|
||||
|
||||
private ShieldData _data;
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): "a shield hit is not an activation the player chose, so its
|
||||
// 'instant' draw is really a continuous reserve. Name it as such rather than giving it an activation
|
||||
// buffer." Unlike InstantWeapon/Sensor above, TrySpend below is never called with exactly Capacity -- a hit
|
||||
// can partially draw the reserve, same as the old direct capacitor spend could. Shield has no Energy/
|
||||
// Cooldown pair to derive a size from (only EnergyUsage, a per-damage-point multiplier), so this is a
|
||||
// judgment call, not a formula the map states: the reserve's Capacity and Rate both default to EnergyUsage
|
||||
// itself, refilling in full every second (Cooldown's implicit identity value -- the same "absent means
|
||||
// identity" convention InputCapacitor and PerformanceStat itself already use). Flagged for operator review
|
||||
// against real catalog EnergyUsage magnitudes rather than presented as spec'd.
|
||||
private readonly InputCapacitor _reserve = new InputCapacitor();
|
||||
|
||||
public Shield(ShieldData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
|
|
@ -42,24 +53,44 @@ public class Shield : Behavior, IProgressBehavior
|
|||
_data = data;
|
||||
}
|
||||
|
||||
// Cut 4: capacity/rate, resolved fresh (Capacitor.ResolveCapacity's precedent -- PowerBus.Step calls
|
||||
// PowerRequest below before this behaviour's own Execute runs this tick).
|
||||
private void RefreshReserve()
|
||||
{
|
||||
var energyUsage = Evaluate(_data.EnergyUsage);
|
||||
_reserve.UpdateStats(energyUsage, cooldown: 1f);
|
||||
}
|
||||
|
||||
// Cut 4: the request PowerBus needs before Execute runs.
|
||||
public float PowerRequest(float dt)
|
||||
{
|
||||
RefreshReserve();
|
||||
return _reserve.RequestedFill(dt);
|
||||
}
|
||||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
Efficiency = Evaluate(_data.Efficiency);
|
||||
EnergyUsage = Evaluate(_data.EnergyUsage);
|
||||
// Cut 4: this tick's grant, read back via Item.PowerSupply -- Item is non-null here because a null-Item
|
||||
// instance never reaches PowerBus.Step (see CanTakeHit/TakeHit) and so never accrues charge.
|
||||
if (Item != null)
|
||||
_reserve.AddCharge(_reserve.RequestedFill(dt) * Item.PowerSupply);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Cut 3 (docs/stats-and-power-cut.md): one of the four instant draws out of scope for the bus this cut (a
|
||||
// hit taken, not a chosen activation) -- named, temporary exception, spending capacitor charge directly
|
||||
// instead of through PowerBus. Cut 4 gives it a real continuous reserve model and closes this.
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): a hit taken, not a chosen activation, drawing from the
|
||||
// shield's own continuous reserve instead of the entity's shared bus capacitors -- closing Cut 3's named,
|
||||
// temporary exception. A consumable-hosted instance (Item == null) has no PowerBus entry, so nothing would
|
||||
// ever fill this reserve; bypass it rather than starving such an instance forever.
|
||||
public bool CanTakeHit(DamageType type, float damage)
|
||||
{
|
||||
return Entity.CanSpendCapacitorCharge(damage * EnergyUsage);
|
||||
return Item == null || _reserve.CanSpend(damage * EnergyUsage);
|
||||
}
|
||||
|
||||
public void TakeHit(DamageType type, float damage)
|
||||
{
|
||||
Entity.TrySpendCapacitorCharge(damage * EnergyUsage);
|
||||
if (Item != null) _reserve.TrySpend(damage * EnergyUsage);
|
||||
AddHeat(damage / Efficiency);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -78,7 +78,6 @@ public abstract class Entity
|
|||
|
||||
private EquippedItem[] _orderedEquipment;
|
||||
private List<Weapon> _weapons = new List<Weapon>();
|
||||
private List<Capacitor> _capacitors = new List<Capacitor>();
|
||||
private List<Radiator> _heatsinks = new List<Radiator>();
|
||||
|
||||
private List<ConsumableItemEffect> _activeConsumables = new List<ConsumableItemEffect>();
|
||||
|
|
@ -610,8 +609,6 @@ public abstract class Entity
|
|||
_weapons.Remove(weapon);
|
||||
foreach (var group in WeaponGroups) { group.items.Remove(item); group.weapons.Remove(weapon); }
|
||||
}
|
||||
if (b is Capacitor capacitor)
|
||||
_capacitors.Remove(capacitor);
|
||||
if (b is Radiator heatsink)
|
||||
_heatsinks.Remove(heatsink);
|
||||
if (b is Shield)
|
||||
|
|
@ -793,8 +790,6 @@ public abstract class Entity
|
|||
{
|
||||
if (b is Weapon weapon)
|
||||
_weapons.Add(weapon);
|
||||
if(b is Capacitor capacitor)
|
||||
_capacitors.Add(capacitor);
|
||||
if(b is Radiator heatsink)
|
||||
_heatsinks.Add(heatsink);
|
||||
if (b is Shield shield)
|
||||
|
|
@ -858,37 +853,11 @@ public abstract class Entity
|
|||
return true;
|
||||
}
|
||||
|
||||
// Cut 3 (docs/stats-and-power-cut.md): replaces CanConsumeEnergy/TryConsumeEnergy for the four instant draws
|
||||
// the cut map names as out of scope for the bus this cut (a burst, a shot, a ping, a hit taken) -- the named,
|
||||
// temporary exception the map accepts, closed by Cut 4's input capacitors. Capacitor charge only: a reactor
|
||||
// no longer bails out a draw it cannot cover for free, which is exactly the behaviour Cut 3 exists to remove
|
||||
// (§0.5 -- "every draw succeeds while one reactor is online"). Atomic: either every capacitor together holds
|
||||
// enough charge and it is spent, or nothing moves -- never TryConsumeEnergy's old partial drain-then-refuse.
|
||||
public bool CanSpendCapacitorCharge(float energy) => _capacitors.Sum(cap => cap.Charge) >= energy;
|
||||
|
||||
public bool TrySpendCapacitorCharge(float energy)
|
||||
{
|
||||
if (energy < .01f) return true;
|
||||
if (!CanSpendCapacitorCharge(energy)) return false;
|
||||
|
||||
var remaining = energy;
|
||||
int chargedCapacitors;
|
||||
do
|
||||
{
|
||||
chargedCapacitors = _capacitors.Count(capacitor => capacitor.Charge > .01f);
|
||||
if (chargedCapacitors == 0) break;
|
||||
var share = remaining / chargedCapacitors;
|
||||
foreach (var cap in _capacitors)
|
||||
{
|
||||
if (cap.Charge <= .01f) continue;
|
||||
var drawn = min(share, cap.Charge);
|
||||
cap.AddCharge(-drawn);
|
||||
remaining -= drawn;
|
||||
}
|
||||
} while (chargedCapacitors > 0 && remaining > .01f);
|
||||
|
||||
return true;
|
||||
}
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): CanSpendCapacitorCharge/TrySpendCapacitorCharge died here with
|
||||
// their last caller. Cut 3 named them a temporary exception for the four instant draws (a burst, a shot, a
|
||||
// ping, a hit taken); all four now spend from their own InputCapacitor instead (InstantWeapon, Sensor,
|
||||
// Shield), fed continuously by PowerBus like every other consumer. The entity's shared bus capacitors are
|
||||
// now touched only by PowerBus itself (§0b: "the bus fills; the owning behaviour spends").
|
||||
|
||||
private void AddChild(Entity entity)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -16,9 +16,10 @@ using static CultMath.math;
|
|||
// (§0.5), not a replacement for it.
|
||||
//
|
||||
// Bus capacitors are charged and drained only here (§0b): Reactor no longer touches them, and neither does any
|
||||
// IPowerConsumer. The four instant draws the cut map names (a burst, a shot, a ping, a hit taken) are out of
|
||||
// scope for this cut and spend capacitor charge directly instead, through Entity.TrySpendCapacitorCharge -- a
|
||||
// named, temporary exception this cut accepts, closed by Cut 4.
|
||||
// IPowerConsumer. The four instant draws the cut map names (a burst, a shot, a ping, a hit taken) are
|
||||
// IPowerConsumers too as of Cut 4: each spends from its own InputCapacitor (InstantWeapon, Sensor, Shield),
|
||||
// never from these bus capacitors directly. Entity.TrySpendCapacitorCharge/CanSpendCapacitorCharge, Cut 3's
|
||||
// named, temporary exception, died with their last caller.
|
||||
public class PowerBus
|
||||
{
|
||||
private readonly Entity _entity;
|
||||
|
|
|
|||
279
tests/Aetheria.Shared.Tests/InputCapacitorTests.cs
Normal file
279
tests/Aetheria.Shared.Tests/InputCapacitorTests.cs
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using Xunit;
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4): closes Cut 3's named, temporary exception for the four instant
|
||||
// draws (a burst, a shot, a ping, a hit taken) -- each now spends from its own InputCapacitor, fed continuously
|
||||
// by PowerBus like every other consumer, instead of the entity's shared bus capacitors directly. This file pins
|
||||
// Cut 4's own verification bullets ("no item ever receives a fraction of a shot"; halving the grant halves the
|
||||
// sustained rate of fire without changing damage per shot) plus the atomicity and half-charge-under-brownout
|
||||
// rules the map's per-file notes require. Each rule has a matching mutation in
|
||||
// tests/mutation_tests_stats_power_cut4.py.
|
||||
public sealed class InputCapacitorTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-inputcap-" + Guid.NewGuid().ToString("N"));
|
||||
private string Catalog => Path.Combine(_root, "Aetheria.cc");
|
||||
|
||||
public InputCapacitorTests() => Directory.CreateDirectory(_root);
|
||||
public void Dispose() => Directory.Delete(_root, true);
|
||||
|
||||
private static GameplaySettings Settings() => new GameplaySettings
|
||||
{
|
||||
DefaultEntitySettings = new EntitySettings(),
|
||||
Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } },
|
||||
QualityPriceModifier = new ExponentialLerp()
|
||||
};
|
||||
|
||||
private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v };
|
||||
|
||||
// Same fixture shape as PowerBusTests.OpenCatalog (see its comment for why): a 3x3 interior hull, wide heat
|
||||
// bounds so ThermalOnline never has to be exercised, and a Reactor whose Charge this method leaves at 0 --
|
||||
// BuildShip below sets the actual generation per test.
|
||||
private CultCache OpenCatalog()
|
||||
{
|
||||
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
var hullShape = new Shape(5, 5);
|
||||
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
|
||||
cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10, Mass = 1000 });
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Reactor", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
|
||||
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
|
||||
Behaviors = { new ReactorData
|
||||
{
|
||||
Charge = Constant(0), Efficiency = Constant(1), OverloadEfficiency = Constant(1), ThrottlingFactor = Constant(2)
|
||||
} }
|
||||
});
|
||||
// BurstCount and Cooldown must be authored: InstantWeapon.UpdateStats divides Damage/Heat/Energy by
|
||||
// (int)BurstCount and Execute divides dt by Cooldown, so the catalog's own zero-valued PerformanceStat
|
||||
// default is not a usable fixture value here (unlike Reactor/Capacitor above, which tolerate it).
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Gun", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
|
||||
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
|
||||
Behaviors = { new InstantWeaponData
|
||||
{
|
||||
Count = Constant(1), Cooldown = Constant(1), Energy = Constant(10), MagazineSize = 0
|
||||
} }
|
||||
});
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Shield", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
|
||||
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
|
||||
Behaviors = { new ShieldData { Efficiency = Constant(1), EnergyUsage = Constant(1) } }
|
||||
});
|
||||
cache.FlushAsync().Wait();
|
||||
return cache;
|
||||
}
|
||||
|
||||
private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design) => new EquippableItem
|
||||
{
|
||||
Data = cache.RefOf<ItemData>(design),
|
||||
Durability = design is EquippableItemData equippable ? equippable.Durability : 0,
|
||||
Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(design), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
|
||||
};
|
||||
|
||||
private (Ship ship, ItemManager items, Reactor reactor) BuildShip(CultCache cache, float reactorCharge)
|
||||
{
|
||||
var ledger = new ProvenanceLedger();
|
||||
var items = new ItemManager(cache, ledger, Settings(), _ => { });
|
||||
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
|
||||
var hull = Mint(cache, items, cache.GetByName<HullData>("Skiff"));
|
||||
var ship = new Ship(items, zone, hull, new EntitySettings());
|
||||
|
||||
var reactorData = cache.GetByName<GearData>("Reactor");
|
||||
((ReactorData) reactorData.Behaviors[0]).Charge = Constant(reactorCharge);
|
||||
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, reactorData)));
|
||||
|
||||
zone.Entities.Add(ship);
|
||||
ship.Activate();
|
||||
|
||||
return (ship, items, ship.GetBehavior<Reactor>());
|
||||
}
|
||||
|
||||
private InstantWeapon EquipGun(CultCache cache, Ship ship)
|
||||
{
|
||||
var gunData = cache.GetByName<GearData>("Gun");
|
||||
ship.Deactivate();
|
||||
Assert.True(ship.TryEquip(Mint(cache, ship.ItemManager, gunData)));
|
||||
ship.Activate();
|
||||
return ship.GetBehavior<InstantWeapon>();
|
||||
}
|
||||
|
||||
private Shield EquipShield(CultCache cache, Ship ship)
|
||||
{
|
||||
var shieldData = cache.GetByName<GearData>("Shield");
|
||||
ship.Deactivate();
|
||||
Assert.True(ship.TryEquip(Mint(cache, ship.ItemManager, shieldData)));
|
||||
ship.Activate();
|
||||
return ship.GetBehavior<Shield>();
|
||||
}
|
||||
|
||||
// Cut 4's own verification bullet: "a weapon whose input capacitor is partly filled does not fire a
|
||||
// partial shot." Gun costs 10 energy/shot with a 1s cooldown (Rate = 10/s); a 5-generation reactor fills
|
||||
// the capacitor to exactly half (5) after one second -- not enough to fire, and not a rejected-but-costly
|
||||
// attempt either: ammo/heat/cooldown state must be completely untouched.
|
||||
[Fact]
|
||||
public void WeaponDoesNotFireOnAPartialCharge()
|
||||
{
|
||||
using var cache = OpenCatalog();
|
||||
var (ship, _, _) = BuildShip(cache, reactorCharge: 5);
|
||||
var gun = EquipGun(cache, ship);
|
||||
var fired = false;
|
||||
gun.OnFire += () => fired = true;
|
||||
|
||||
// Trigger() reads BurstCount/Cooldown off cached properties that only exist after UpdateStats has run
|
||||
// once (inside Execute) -- a zero-dt warm-up tick populates them without spending any time or charge,
|
||||
// the same role PowerBusTests.BuildShip's own warm-up tick plays for Capacitor.Capacity.
|
||||
ship.Update(0f);
|
||||
|
||||
// Arm the burst BEFORE the tick that charges the capacitor: InstantWeapon.Execute adds this tick's
|
||||
// grant and then runs its burst loop in the same call, so a single dt=1 tick both fills the capacitor
|
||||
// to exactly half (5 of 10) and attempts the shot against that same half charge -- proving the failure
|
||||
// is read from the charge actually banked this tick, not a stale or optimistic value.
|
||||
gun.Activate();
|
||||
ship.Update(1f); // capacitor request = 10, granted 5 -> half charge, then the burst loop's own attempt
|
||||
|
||||
Assert.False(fired);
|
||||
}
|
||||
|
||||
// The other half of the same rule: once the reactor can cover a full second's worth (10 generation), the
|
||||
// capacitor reaches exactly Capacity in the same tick the burst loop runs, and the shot goes through.
|
||||
[Fact]
|
||||
public void WeaponFiresOnceFullyCharged()
|
||||
{
|
||||
using var cache = OpenCatalog();
|
||||
var (ship, _, _) = BuildShip(cache, reactorCharge: 10);
|
||||
var gun = EquipGun(cache, ship);
|
||||
var fired = false;
|
||||
gun.OnFire += () => fired = true;
|
||||
|
||||
ship.Update(0f); // warm-up: populates BurstCount/Cooldown before Trigger() reads them
|
||||
gun.Activate();
|
||||
ship.Update(1f); // capacitor request = 10, granted 10 -> full charge, then the burst loop fires
|
||||
|
||||
Assert.True(fired);
|
||||
}
|
||||
|
||||
// Cut 4's other verification bullet: "halving the grant halves the refill rate ... without changing damage
|
||||
// per shot." Pinned directly on InputCapacitor -- the mechanism PowerBus and every owning behaviour's
|
||||
// Execute drive identically (RequestedFill(dt) for the request, AddCharge(request * PowerSupply) for the
|
||||
// fill) -- rather than on a full ship simulation, whose demand naturally shrinks as a capacitor tops up and
|
||||
// so does not hold a constant grant fraction across ticks.
|
||||
[Fact]
|
||||
public void HalvingTheGrantHalvesTheChargeBankedWithoutChangingCapacity()
|
||||
{
|
||||
var full = new InputCapacitor();
|
||||
full.UpdateStats(energy: 10f, cooldown: 1f); // Capacity = 10, Rate = 10/s
|
||||
var half = new InputCapacitor();
|
||||
half.UpdateStats(energy: 10f, cooldown: 1f);
|
||||
|
||||
var fullRequest = full.RequestedFill(.1f);
|
||||
var halfRequest = half.RequestedFill(.1f);
|
||||
Assert.Equal(fullRequest, halfRequest, 5); // identical ask -- only the grant differs
|
||||
|
||||
full.AddCharge(fullRequest * 1f); // PowerSupply == 1: full grant
|
||||
half.AddCharge(halfRequest * .5f); // PowerSupply == .5: half grant
|
||||
|
||||
Assert.Equal(2f * half.Charge, full.Charge, 4); // half the grant banks exactly half the charge
|
||||
Assert.Equal(10f, full.Capacity, 3);
|
||||
Assert.Equal(10f, half.Capacity, 3); // per-shot cost (Capacity) is unaffected by the grant
|
||||
}
|
||||
|
||||
// A half-charged item's own reserve neither drains nor advances on its own when the bus grants nothing
|
||||
// (Item.PowerSupply == 0, e.g. under total brownout): AddCharge(0) must be a true no-op, not a slow leak or
|
||||
// a forced top-up. Exercised directly on InputCapacitor -- the unit under test PowerBus.Step and every
|
||||
// owning behaviour's Execute both call into.
|
||||
[Fact]
|
||||
public void HalfChargedCapacitorHoldsItsChargeWhenNothingIsGranted()
|
||||
{
|
||||
var capacitor = new InputCapacitor();
|
||||
capacitor.UpdateStats(energy: 10f, cooldown: 1f);
|
||||
capacitor.AddCharge(5f);
|
||||
Assert.Equal(5f, capacitor.Charge, 3);
|
||||
|
||||
capacitor.AddCharge(0f); // the bus granted nothing this tick
|
||||
Assert.Equal(5f, capacitor.Charge, 3);
|
||||
Assert.False(capacitor.TrySpend(capacitor.Capacity)); // still can't fire on half charge
|
||||
Assert.Equal(5f, capacitor.Charge, 3); // and the refused attempt did not touch it
|
||||
}
|
||||
|
||||
// AddCharge must clamp to Capacity -- the bus over-filling by a rounding error, or a Capacity that shrank
|
||||
// under a stat change after charge had already accumulated, must never leave Charge reporting more energy
|
||||
// than a single activation could ever need.
|
||||
[Fact]
|
||||
public void AddChargeNeverExceedsCapacity()
|
||||
{
|
||||
var capacitor = new InputCapacitor();
|
||||
capacitor.UpdateStats(energy: 10f, cooldown: 1f);
|
||||
|
||||
capacitor.AddCharge(999f);
|
||||
|
||||
Assert.Equal(10f, capacitor.Charge, 3);
|
||||
}
|
||||
|
||||
// InputCapacitor.TrySpend must be atomic -- Entity.TrySpendCapacitorCharge's old contract, now scoped to
|
||||
// one behaviour's own buffer: either the cost is covered in full, or Charge is untouched.
|
||||
[Fact]
|
||||
public void TrySpendMovesNothingWhenTheCostCannotBeFullyCovered()
|
||||
{
|
||||
var capacitor = new InputCapacitor();
|
||||
capacitor.UpdateStats(energy: 10f, cooldown: 1f);
|
||||
capacitor.AddCharge(6f);
|
||||
|
||||
Assert.False(capacitor.TrySpend(10f));
|
||||
Assert.Equal(6f, capacitor.Charge, 3);
|
||||
|
||||
Assert.True(capacitor.TrySpend(6f));
|
||||
Assert.Equal(0f, capacitor.Charge, 3);
|
||||
}
|
||||
|
||||
// Q4 (operator ruling): capacity/rate derive from Energy and Cooldown by default, but an authored override
|
||||
// replaces the rate -- ChargedWeapon's own mechanism (RateOverride => ChargeEnergy). Pinned directly on
|
||||
// InputCapacitor: a nonzero rateOverride wins over the Capacity/cooldown default.
|
||||
[Fact]
|
||||
public void RateOverrideReplacesTheDerivedDefault()
|
||||
{
|
||||
var derived = new InputCapacitor();
|
||||
derived.UpdateStats(energy: 10f, cooldown: 2f); // default rate = 10/2 = 5
|
||||
Assert.Equal(5f, derived.Rate, 3);
|
||||
|
||||
var overridden = new InputCapacitor();
|
||||
overridden.UpdateStats(energy: 10f, cooldown: 2f, rateOverride: 100f);
|
||||
Assert.Equal(100f, overridden.Rate, 3);
|
||||
}
|
||||
|
||||
// Shield is the map's named "odd one out": a hit is not a chosen activation, so its reserve is a continuous
|
||||
// one, not an activation buffer -- CanTakeHit/TakeHit may draw an arbitrary fraction of the reserve (never
|
||||
// "must be exactly Capacity" the way a weapon's shot must). But the underlying spend is still atomic: a hit
|
||||
// costing more than the whole reserve holds is refused entirely, not partially absorbed.
|
||||
[Fact]
|
||||
public void ShieldReserveAllowsAPartialDrawButRefusesAHitItCannotFullyCover()
|
||||
{
|
||||
using var cache = OpenCatalog();
|
||||
var (ship, _, _) = BuildShip(cache, reactorCharge: 10);
|
||||
var shield = EquipShield(cache, ship);
|
||||
|
||||
ship.Update(1f); // EnergyUsage = 1 -> reserve Capacity = Rate = 1, granted in full -> Charge = 1
|
||||
|
||||
// A small hit (cost 0.5, well under the 1-unit reserve) is a legitimate partial draw, unlike a weapon
|
||||
// shot, which is only ever spent whole.
|
||||
Assert.True(shield.CanTakeHit(DamageType.Kinetic, .5f));
|
||||
shield.TakeHit(DamageType.Kinetic, .5f);
|
||||
|
||||
// With .5 left, a smaller hit (0.3) is still absorbed -- this is the assertion that actually
|
||||
// distinguishes "may draw a partial amount" from "requires the reserve to be at full Capacity", the
|
||||
// rule the map draws between Shield and the weapon/sensor buffers above.
|
||||
Assert.True(shield.CanTakeHit(DamageType.Kinetic, .3f));
|
||||
|
||||
// A hit needing more than what's left (0.5 remains, hit costs 1) is refused outright, not partially
|
||||
// absorbed.
|
||||
Assert.False(shield.CanTakeHit(DamageType.Kinetic, 1f));
|
||||
}
|
||||
}
|
||||
|
|
@ -9,9 +9,12 @@ using Xunit;
|
|||
// Cut 3 (docs/stats-and-power-cut.md): the power bus replaces Entity.TryConsumeEnergy/CanConsumeEnergy. At HEAD
|
||||
// every draw succeeded as long as one reactor was online, and any shortfall was silently taxed onto the reactor
|
||||
// as heat (§0.5) -- an assertion pinning "demand beyond supply is refused" was unwritable against that code.
|
||||
// This file pins PowerBus's three verification bullets from the cut map's Cut 3 section, plus the atomicity of
|
||||
// Entity.TrySpendCapacitorCharge, the named exception the four instant draws keep this cut. Each rule has a
|
||||
// This file pins PowerBus's three verification bullets from the cut map's Cut 3 section. Each rule has a
|
||||
// matching mutation in tests/mutation_tests_stats_power_cut3.py.
|
||||
//
|
||||
// Cut 4 (docs/stats-and-power-cut.md, Cut 4) deleted this file's Entity.TrySpendCapacitorCharge atomicity test
|
||||
// along with the method itself -- the named, temporary exception Cut 3 left standing for the four instant
|
||||
// draws is closed; see InputCapacitorTests.cs and mutation_tests_stats_power_cut4.py instead.
|
||||
public sealed class PowerBusTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-powerbus-" + Guid.NewGuid().ToString("N"));
|
||||
|
|
@ -205,20 +208,4 @@ public sealed class PowerBusTests : IDisposable
|
|||
Assert.Equal(ship.PowerBus.GrantRatio, drainOne.PowerSupply, 5);
|
||||
Assert.Equal(ship.PowerBus.GrantRatio, drainTwo.PowerSupply, 5);
|
||||
}
|
||||
|
||||
// --- Entity.TrySpendCapacitorCharge (the four instant draws' named, temporary exception, §Cut 3): atomic --
|
||||
// --- either every capacitor together holds enough charge and it is spent, or nothing moves. This is the
|
||||
// --- exact bug TryConsumeEnergy had (a partial drain-then-refuse) that the cut map calls out by name. ---
|
||||
[Fact]
|
||||
public void TrySpendCapacitorChargeMovesNothingWhenTheRequestCannotBeFullyCovered()
|
||||
{
|
||||
using var cache = OpenCatalog();
|
||||
var (ship, _, _, capacitor) = BuildShip(cache, reactorCharge: 0, startingCapacitorCharge: 5, reactorFirst: true);
|
||||
|
||||
Assert.False(ship.TrySpendCapacitorCharge(10f));
|
||||
Assert.Equal(5f, capacitor.Charge, 3); // untouched -- not partially drained toward the refused request
|
||||
|
||||
Assert.True(ship.TrySpendCapacitorCharge(5f));
|
||||
Assert.Equal(0f, capacitor.Charge, 3);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -94,21 +94,10 @@ MUTATIONS: list[Mutation] = [
|
|||
expect="red",
|
||||
),
|
||||
|
||||
# --- Entity.TrySpendCapacitorCharge (the four instant draws' named, temporary exception, §Cut 3 per-file
|
||||
# --- changes): atomic -- either every capacitor together holds enough charge and it is spent, or nothing
|
||||
# --- moves. Deleting the upfront capacity check restores TryConsumeEnergy's old bug: the do/while below
|
||||
# --- drains whatever charge exists toward a request it can never fully pay, then still reports failure. ---
|
||||
Mutation(
|
||||
rule="TrySpendCapacitorCharge must refuse before draining anything it cannot fully cover",
|
||||
file="Assets/Scripts/ServerShared/Entity.cs",
|
||||
anchor=(
|
||||
" if (energy < .01f) return true;\n"
|
||||
" if (!CanSpendCapacitorCharge(energy)) return false;"
|
||||
),
|
||||
mutated=" if (energy < .01f) return true;",
|
||||
test="PowerBusTests.TrySpendCapacitorChargeMovesNothingWhenTheRequestCannotBeFullyCovered",
|
||||
expect="red",
|
||||
),
|
||||
# Entity.TrySpendCapacitorCharge/CanSpendCapacitorCharge -- the four instant draws' named, temporary
|
||||
# exception this file used to pin -- died with their last caller in Cut 4
|
||||
# (docs/stats-and-power-cut.md, Cut 4). See mutation_tests_stats_power_cut4.py's InputCapacitor.TrySpend
|
||||
# case for the same atomicity rule, now scoped to each behaviour's own buffer.
|
||||
]
|
||||
|
||||
|
||||
|
|
|
|||
196
tests/mutation_tests_stats_power_cut4.py
Normal file
196
tests/mutation_tests_stats_power_cut4.py
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Mutation tests for docs/stats-and-power-cut.md Cut 4 (all draw is continuous -- input capacitors).
|
||||
|
||||
Cut 4 closes Cut 3's named, temporary exception for the four instant draws (a burst, a shot, a ping, a hit
|
||||
taken): each now spends from its own InputCapacitor, fed continuously by PowerBus like every other consumer,
|
||||
instead of the entity's shared bus capacitors directly through the now-deleted
|
||||
Entity.TrySpendCapacitorCharge/CanSpendCapacitorCharge. This script mutates each rule's own line of code and
|
||||
asserts the named test in InputCapacitorTests.cs goes red for exactly that reason. A no-op control mutation
|
||||
proves the read/replace/restore path is transparent.
|
||||
|
||||
Usage:
|
||||
python tests/mutation_tests_stats_power_cut4.py --cultlib-root <path-to-CultLib-45c2f40-worktree>
|
||||
|
||||
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"
|
||||
|
||||
|
||||
@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="Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs",
|
||||
anchor=" public void AddCharge(float amount) => Charge = clamp(Charge + amount, 0f, Capacity);",
|
||||
mutated=" public void AddCharge(float amount) => Charge = clamp(Charge + amount, 0f, Capacity);",
|
||||
test="InputCapacitorTests.AddChargeNeverExceedsCapacity",
|
||||
expect="green",
|
||||
),
|
||||
|
||||
# --- AddCharge must clamp to Capacity: an input capacitor is sized to exactly one activation, so nothing
|
||||
# --- (a rounding surplus, a Capacity that shrank after charge had already banked) may ever report more
|
||||
# --- charge than one activation could use. ---
|
||||
Mutation(
|
||||
rule="AddCharge must clamp to Capacity",
|
||||
file="Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs",
|
||||
anchor=" public void AddCharge(float amount) => Charge = clamp(Charge + amount, 0f, Capacity);",
|
||||
mutated=" public void AddCharge(float amount) => Charge = Charge + amount;",
|
||||
test="InputCapacitorTests.AddChargeNeverExceedsCapacity",
|
||||
expect="red",
|
||||
),
|
||||
|
||||
# --- TrySpend must refuse before moving anything it cannot fully cover -- the exact atomicity contract
|
||||
# --- Entity.TrySpendCapacitorCharge had, now scoped to one behaviour's own buffer. Deleting the upfront
|
||||
# --- check restores the old TryConsumeEnergy-class bug: a cost this buffer cannot fully pay would still
|
||||
# --- partially drain it. ---
|
||||
Mutation(
|
||||
rule="TrySpend must refuse before spending anything it cannot fully cover",
|
||||
file="Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs",
|
||||
anchor=(
|
||||
" if (cost < .01f) return true;\n"
|
||||
" if (!CanSpend(cost)) return false;"
|
||||
),
|
||||
mutated=" if (cost < .01f) return true;",
|
||||
test="InputCapacitorTests.TrySpendMovesNothingWhenTheCostCannotBeFullyCovered",
|
||||
expect="red",
|
||||
),
|
||||
|
||||
# --- Default rate derives from Capacity/cooldown (Q4 ruling: "derived from energy and cooldown"). Dropping
|
||||
# --- the division collapses the derived rate to Capacity itself (refill in 1 second regardless of the
|
||||
# --- weapon's own cooldown), which RateOverrideReplacesTheDerivedDefault pins directly. ---
|
||||
Mutation(
|
||||
rule="the default rate must derive from Capacity/cooldown, not just Capacity",
|
||||
file="Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs",
|
||||
anchor=" Rate = rateOverride > 0f ? rateOverride : (cooldown > 0f ? Capacity / cooldown : Capacity);",
|
||||
mutated=" Rate = rateOverride > 0f ? rateOverride : Capacity;",
|
||||
test="InputCapacitorTests.RateOverrideReplacesTheDerivedDefault",
|
||||
expect="red",
|
||||
),
|
||||
|
||||
# --- Cut 4's own verification bullet: "a weapon whose input capacitor is partly filled does not fire a
|
||||
# --- partial shot." A fire attempt must spend exactly Capacity -- never a lesser, possibly-partial amount
|
||||
# --- -- so it only ever succeeds at full charge. Spending 0 instead bypasses the whole-shot requirement:
|
||||
# --- every attempt would "succeed" regardless of charge. ---
|
||||
Mutation(
|
||||
rule="a fire attempt must spend exactly Capacity, never a lesser amount",
|
||||
file="Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs",
|
||||
anchor=" protected bool TrySpendActivationEnergy() => Item == null || _capacitor.TrySpend(_capacitor.Capacity);",
|
||||
mutated=" protected bool TrySpendActivationEnergy() => Item == null || _capacitor.TrySpend(0f);",
|
||||
test="InputCapacitorTests.WeaponDoesNotFireOnAPartialCharge",
|
||||
expect="red",
|
||||
),
|
||||
|
||||
# --- The other half of the same rule, at the fill site instead of the spend site: the capacitor must only
|
||||
# --- ever bank the fraction PowerBus actually granted (Item.PowerSupply), never the whole request
|
||||
# --- regardless of supply -- otherwise a weapon on half power would still reach full charge (and fire) on
|
||||
# --- the very first tick, exactly the "every draw succeeds" bug Cut 3 exists to remove, just relocated. ---
|
||||
Mutation(
|
||||
rule="the capacitor must only bank the fraction PowerBus actually granted, not the whole request",
|
||||
file="Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs",
|
||||
anchor=" _capacitor.AddCharge(_capacitor.RequestedFill(dt) * Item.PowerSupply);",
|
||||
mutated=" _capacitor.AddCharge(_capacitor.RequestedFill(dt));",
|
||||
test="InputCapacitorTests.WeaponDoesNotFireOnAPartialCharge",
|
||||
expect="red",
|
||||
),
|
||||
|
||||
# --- Shield is the map's named exception: a hit is not a chosen activation, so its reserve is a continuous
|
||||
# --- one that may absorb an arbitrary fraction of a hit's cost, unlike a weapon's shot (always spent
|
||||
# --- whole). Requiring a hit to cover the WHOLE reserve before absorbing anything collapses that
|
||||
# --- distinction back into an activation buffer, which the map explicitly says not to give it. ---
|
||||
Mutation(
|
||||
rule="the shield reserve must allow a partial draw, not require a full reserve before absorbing a hit",
|
||||
file="Assets/Scripts/ServerShared/Behaviors/Shield.cs",
|
||||
anchor=" return Item == null || _reserve.CanSpend(damage * EnergyUsage);",
|
||||
mutated=" return Item == null || _reserve.CanSpend(_reserve.Capacity);",
|
||||
test="InputCapacitorTests.ShieldReserveAllowsAPartialDrawButRefusesAHitItCannotFullyCover",
|
||||
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())
|
||||
Loading…
Reference in a new issue