diff --git a/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs b/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs index c81c63c16..9efa1207b 100644 --- a/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs +++ b/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs @@ -111,6 +111,9 @@ public class AetherDrive : Behavior, IPowerConsumer return (draw.x + draw.y + draw.z) * dt; } + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Medium -- mobility, same as Thruster. + public int DefaultPowerTier => PowerTiers.Medium; + public override bool Execute(float dt) { var rotorSpeed = Rpm * _data.RotorDiameter / 100; diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 2cc6be088..714a64e12 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -124,11 +124,6 @@ public interface IProgressBehavior float Progress { get; } } -public interface IOrderedBehavior -{ - int Order { get; } -} - public interface IPopulationAssignment { int AssignedPopulation { get; set; } @@ -140,9 +135,14 @@ public interface IPopulationAssignment // point -- a resolved stat and, where the map calls for one, a behaviour-supplied scalar such as Thruster's // throttle axis (set externally before the tick) -- never from work Execute itself would otherwise do. The // behaviour reads back how much of its own request was granted from Item.PowerSupply during its own Execute. +// +// Cut 5 (docs/stats-and-power-cut.md §1.3): every kind of consumer also names the priority tier (PowerTiers.cs) +// it defaults to. EquippedItem reads this exactly once, to seed EquippableItem.PowerTier the first time an item +// without a player-chosen tier gets equipped -- after that the stored field is what PowerBus reads, never this. public interface IPowerConsumer { float PowerRequest(float dt); + int DefaultPowerTier { get; } } [Inspectable, diff --git a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs index a1a9191b8..83fddfc52 100644 --- a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs @@ -77,6 +77,9 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC // Deactivate) before Entity.Update calls PowerBus.Step, so it is already current when this runs. public float PowerRequest(float dt) => _firing && StanceAllowsFire ? Evaluate(_data.Energy) * dt : 0f; + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Low -- offense, same as InstantWeapon. + public int DefaultPowerTier => PowerTiers.Low; + public override bool Execute(float dt) { base.Execute(dt); diff --git a/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs b/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs index 7f1bb5ea3..ceb535903 100644 --- a/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs +++ b/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs @@ -45,6 +45,10 @@ public class EnergyDraw : Behavior, IPowerConsumer // direct Entity.TryConsumeEnergy spend that used to happen inside Execute. public float PowerRequest(float dt) => Evaluate(_data.EnergyDraw) * (_data.PerSecond ? dt : 1); + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Utility -- the generic/unclassified draw. An item + // that declares power use without asking for a specific tier should not accidentally outrank a named one. + public int DefaultPowerTier => PowerTiers.Utility; + public override bool Execute(float dt) { // A consumable-hosted instance (Item null) has no PowerBus entry (§1.2's grants are keyed by diff --git a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs index 5630277bb..cd4f0def0 100644 --- a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs @@ -143,6 +143,10 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo return _capacitor.RequestedFill(dt); } + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Low -- offense. The ruling's own example of what + // a reactor throttle should sacrifice first. + public int DefaultPowerTier => PowerTiers.Low; + // 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 diff --git a/Assets/Scripts/ServerShared/Behaviors/Radiator.cs b/Assets/Scripts/ServerShared/Behaviors/Radiator.cs index 8412d382b..868139ef8 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Radiator.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Radiator.cs @@ -70,6 +70,10 @@ public class Radiator : Behavior, IAlwaysUpdatedBehavior, IInitializableBehavior return Evaluate(_data.EnergyUsage) * tempRatio * dt; } + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Critical -- the closest thing this game has to + // life support. A starved radiator cascades into wear and shutdown across every other item on the hull. + public int DefaultPowerTier => PowerTiers.Critical; + public override bool Execute(float dt) { PumpedHeat = Evaluate(_data.PumpedHeat); diff --git a/Assets/Scripts/ServerShared/Behaviors/Reactor.cs b/Assets/Scripts/ServerShared/Behaviors/Reactor.cs index 1fddd3c4e..e5321ac17 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Reactor.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Reactor.cs @@ -34,7 +34,7 @@ public class ReactorData : BehaviorData } } -public class Reactor : Behavior, IOrderedBehavior +public class Reactor : Behavior { private ReactorData _data; @@ -44,8 +44,9 @@ public class Reactor : Behavior, IOrderedBehavior public float CurrentLoadRatio { get; private set; } - public int Order => 100; - + // Cut 5 (docs/stats-and-power-cut.md §1.3): IOrderedBehavior/Order (was 100, the highest, so Reactor always + // ran last) is deleted -- the bus now steps before any equipment's Execute regardless of order, and nothing + // else claimed IOrderedBehavior, so the whole interface goes with its only implementer (§7 O3). public Reactor(ReactorData data, EquippedItem item) : base(data, item) { _data = data; diff --git a/Assets/Scripts/ServerShared/Behaviors/Sensor.cs b/Assets/Scripts/ServerShared/Behaviors/Sensor.cs index 024afdd9a..547da7909 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Sensor.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Sensor.cs @@ -100,6 +100,9 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer return _capacitor.RequestedFill(dt); } + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Utility -- everything else. + public int DefaultPowerTier => PowerTiers.Utility; + public void Ping() { // Whole-or-nothing against the ping's own input capacitor -- fires only at full charge (operator diff --git a/Assets/Scripts/ServerShared/Behaviors/Shield.cs b/Assets/Scripts/ServerShared/Behaviors/Shield.cs index 8960f11a1..0818f0377 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Shield.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Shield.cs @@ -105,6 +105,10 @@ public class Shield : Behavior, IProgressBehavior, IPowerConsumer return _reserve.RequestedFill(dt); } + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): High -- hull survival the player is actively + // trading power for, but not the life-support constant Radiator is, so it sits one tier below. + public int DefaultPowerTier => PowerTiers.High; + public override bool Execute(float dt) { Efficiency = Evaluate(_data.Efficiency); diff --git a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs index 981e6e6ca..b11453137 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs @@ -76,6 +76,10 @@ public class Thruster : Behavior, IAnalogBehavior, IPowerConsumer // PowerBus.Step, so it is already current when this runs. public float PowerRequest(float dt) => _input > .01f ? _input * Evaluate(_data.EnergyUsage) : 0f; + // Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Medium -- mobility. Losing thrust for a tick + // under brownout is an inconvenience, not the cascading failure a starved radiator or shield causes. + public int DefaultPowerTier => PowerTiers.Medium; + public override bool Execute(float dt) { Item.SetAudioParameter(SpecialAudioParameter.Intensity, _input); diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 499aac343..40513f9c6 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -591,7 +591,7 @@ public abstract class Entity } Equipment.Remove(item); - _orderedEquipment = Equipment.OrderBy(x => x.SortPosition).ToArray(); + _orderedEquipment = Equipment.ToArray(); var hullData = ItemManager.GetData(Hull) as HullData; var itemData = ItemManager.GetData(item.EquippableItem); @@ -812,7 +812,7 @@ public abstract class Entity } Mass += itemData.Mass; - _orderedEquipment = Equipment.OrderBy(x => x.SortPosition).ToArray(); + _orderedEquipment = Equipment.ToArray(); return true; } @@ -1184,7 +1184,9 @@ public class ConsumableItemEffect : IStatContext // entity and a running simulation behind it. public class EquippedItem : IStatContext { - public int SortPosition; + // SortPosition (Cut 3-era, only ever set by Reactor.Order) is deleted by Cut 5 (docs/stats-and-power-cut.md + // §1.3): "EquippedItem.SortPosition must no longer influence who is fed" -- the tiered allocation pass + // replaces it, and IOrderedBehavior/Reactor.Order go with it (§7 O3). public EquippableItem EquippableItem; public int2 Position; @@ -1339,11 +1341,19 @@ public class EquippedItem : IStatContext foreach (var behavior in Behaviors) { - if (behavior is IOrderedBehavior orderedBehavior) - SortPosition = orderedBehavior.Order; if(behavior is IPopulationAssignment populationAssignment) entity.PopulationAssignments.Add(populationAssignment); } + + // Cut 5 (docs/stats-and-power-cut.md §1.3, Q5 "defaulted per behaviour kind"): seed the stored tier + // exactly once, the first time this unit is ever equipped. A unit the player has already assigned a + // tier to (or one seeded on an earlier equip) keeps it -- this never runs again for that unit. + if (EquippableItem.PowerTier == PowerTiers.Unassigned) + { + var consumerTiers = Behaviors.OfType().Select(c => c.DefaultPowerTier).ToArray(); + if (consumerTiers.Length > 0) + EquippableItem.PowerTier = consumerTiers.Min(); + } } // Cut 2 (docs/stats-and-power-cut.md): the resolver owns the value; this is the caller's read of it, keyed by diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index 739b7835b..d4e7d9d89 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -52,6 +52,13 @@ public class EquippableItem : CraftedItemInstance { [JsonProperty("durability"), Key(7)] public float Durability; [JsonProperty("override"), Key(8)] public bool OverrideShutdown; + + // Cut 5 (docs/stats-and-power-cut.md §1.3, §0b "A power tier"): a player choice, stored on the unit rather + // than the design, so two units of the same design can be prioritized differently. PowerTiers.Unassigned + // until the first equip seeds a behaviour-kind default (EquippedItem's constructor) or the player overrides + // it from the schematic UI; from then on PowerBus only ever reads it, never derives it. An old run store + // missing key 12 deserializes to this same field initializer, so no migration is needed (§ Cut 5). + [JsonProperty("powerTier"), Key(12)] public int PowerTier = PowerTiers.Unassigned; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/PowerBus.cs b/Assets/Scripts/ServerShared/PowerBus.cs index f6fb386ec..53c1b9d01 100644 --- a/Assets/Scripts/ServerShared/PowerBus.cs +++ b/Assets/Scripts/ServerShared/PowerBus.cs @@ -11,9 +11,14 @@ using static CultMath.math; // 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 instead of ever being refused (§0.5). The bus makes // the ceiling real: demand beyond what this tick's generation and stored capacitor charge can cover goes unmet. -// There are no tiers yet (Cut 5 adds them), so a shortfall rations the whole pool by the same fraction for every -// consumer alike -- the death of the old "whoever equipped first drains the capacitors first" hidden priority -// (§0.5), not a replacement for it. +// +// Cut 5 (docs/stats-and-power-cut.md §1.3) replaces the single shared fraction with priority tiers +// (PowerTiers.cs): the total this tick's supply can cover (TotalGrant, unchanged by tiers -- see below) is +// walked tier by tier, lowest number first. A tier is fed in full before the next tier sees anything left; a +// tier with no demand simply passes its whole share down; within a tier, every consumer's own request is +// rationed by the same fraction, so two requests of unequal size still divide proportionally. This is the death +// of the old "whoever equipped first drains the capacitors first" hidden priority (§0.5), replaced with an +// authored one instead of no priority at all. // // 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 @@ -32,16 +37,34 @@ public class PowerBus public float TotalGeneration { get; private set; } public float TotalDemand { get; private set; } - // Energy actually delivered this tick: generation first, then whatever stored capacitor charge covers the - // rest, capped at demand. Equal to TotalDemand whenever supply covers it; equal to (generation + available - // charge) otherwise -- never more, which TryConsumeEnergy could never promise (a reactor always paid the - // remainder as heat, so overdraw was invisible at this level). + // Energy actually delivered this tick, summed across every tier: generation first, then whatever stored + // capacitor charge covers the rest, capped at demand. Equal to TotalDemand whenever supply covers it; equal + // to (generation + available charge) otherwise -- never more, which TryConsumeEnergy could never promise (a + // reactor always paid the remainder as heat, so overdraw was invisible at this level). Which consumers that + // total actually reaches is what tiering (below) decides; this figure is unaffected by tiers -- the ceiling + // is a property of supply, not of priority. public float TotalGrant { get; private set; } - // Fraction of every consumer's own request actually granted this tick, shared by every consumer alike (no - // tiers yet). Also written onto every consuming EquippedItem.PowerSupply. + // Aggregate fraction of all demand granted this tick (TotalGrant / TotalDemand) -- a fleet-wide summary, not + // what any one consumer necessarily received. Still written onto every consuming EquippedItem.PowerSupply + // when every tier in play happens to land on the same ratio (single-tier loadouts, the common case in the + // Cut 3/4 test fixtures), but a multi-tier shortfall gives different tiers different ratios -- read + // TierGrantRatio or the item's own PowerSupply for that. public float GrantRatio { get; private set; } = 1f; + // Cut 5: this tick's within-tier grant ratio, indexed by PowerTiers.Critical..Utility. 1f means that tier's + // demand was fully met (including a tier with no demand at all, per the array's own default-init); anything + // below 1f is exactly the "starved" state a future UI (Cut 8) reads instead of reconstructing it from + // per-item PowerSupply. A tier below a starved one is always 0f -- §1.3's "a tier boundary does not leak". + public float[] TierGrantRatio { get; } = InitFullTiers(); + + private static float[] InitFullTiers() + { + var ratios = new float[PowerTiers.Count]; + for (var i = 0; i < ratios.Length; i++) ratios[i] = 1f; + return ratios; + } + // What Reactor.Execute reads to run its own heat/throttle arithmetic (Cut 3: "the arithmetic survives, moved // under the bus's numbers"). Positive: demand left unmet after generation AND stored charge, split evenly // across online reactors for overload heat. Negative: generation left over after demand and after topping up @@ -49,11 +72,22 @@ public class PowerBus // a reported total, not a sink (§1.2). public float NetDraw { get; private set; } + // One equipped item's power request for this tick, captured once so PowerRequest -- which some behaviours + // (Shield, InstantWeapon, Sensor) implement by refreshing their own cached stats -- is never called twice in + // one Step. + private readonly struct Draw + { + public readonly EquippedItem Item; + public readonly int Tier; + public readonly float Request; + public Draw(EquippedItem item, int tier, float request) { Item = item; Tier = tier; Request = request; } + } + public void Step(float dt) { var reactors = new List(); var capacitors = new List(); - var consumers = new List(); + var draws = new List(); foreach (var item in _entity.Equipment) foreach (var behavior in item.Behaviors) { @@ -67,11 +101,20 @@ public class PowerBus break; } if (behavior is IPowerConsumer consumer) - consumers.Add(consumer); + { + // Cut 5 (docs/stats-and-power-cut.md §1.3): the item's own stored choice wins once it has one; + // PowerTiers.Unassigned only survives past EquippedItem's constructor for a consumer added to + // the game after this unit was minted, which the constructor never saw -- fall back to the + // behaviour's own default rather than stranding it at an invalid tier. + var tier = item.EquippableItem.PowerTier; + if (tier == PowerTiers.Unassigned) tier = consumer.DefaultPowerTier; + tier = clamp(tier, 0, PowerTiers.Count - 1); + draws.Add(new Draw(item, tier, max(0f, consumer.PowerRequest(dt)))); + } } TotalGeneration = reactors.Sum(r => r.Generation(dt)); - TotalDemand = consumers.Sum(c => max(0f, c.PowerRequest(dt))); + TotalDemand = draws.Sum(d => d.Request); var availableCharge = capacitors.Sum(c => c.Charge); var preCapacitorNet = TotalDemand - TotalGeneration; @@ -92,9 +135,33 @@ public class PowerBus TotalGrant = TotalDemand - overload; GrantRatio = TotalDemand <= 1e-4f ? 1f : saturate(TotalGrant / TotalDemand); - foreach (var item in _entity.Equipment) - if (item.Behaviors.Any(b => b is IPowerConsumer)) - item.PowerSupply = GrantRatio; + AllocateTiers(draws); + } + + // Cut 5 (docs/stats-and-power-cut.md §1.3): walks tiers lowest-number-first, feeding each in full before the + // next sees anything. remaining only ever shrinks, and once it hits 0 every later tier's ratio is 0 by the + // same division -- a lower tier can never take from a higher one (§1.3 "a tier boundary does not leak"), + // because a higher tier's share is committed (remaining -= grant) before a lower tier is even considered. + // Within a tier every consumer shares that tier's one ratio against its own request, so two unequal requests + // still divide proportionally -- the same property Cut 3 proved for the whole ship, now proved per tier. + private void AllocateTiers(List draws) + { + var tierDemand = new float[PowerTiers.Count]; + foreach (var draw in draws) tierDemand[draw.Tier] += draw.Request; + + var remaining = TotalGrant; + var ratios = TierGrantRatio; + for (var tier = 0; tier < PowerTiers.Count; tier++) + { + var demand = tierDemand[tier]; + if (demand <= 1e-4f) { ratios[tier] = 1f; continue; } + var grant = min(demand, remaining); + ratios[tier] = saturate(grant / demand); + remaining -= grant; + } + + foreach (var draw in draws) + draw.Item.PowerSupply = ratios[draw.Tier]; } // Mirrors Entity.TryConsumeEnergy's old do/while exactly (draw evenly across every capacitor that still has diff --git a/Assets/Scripts/ServerShared/PowerTiers.cs b/Assets/Scripts/ServerShared/PowerTiers.cs new file mode 100644 index 000000000..e6bf90d89 --- /dev/null +++ b/Assets/Scripts/ServerShared/PowerTiers.cs @@ -0,0 +1,39 @@ +/* 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/. */ + +// Cut 5 (docs/stats-and-power-cut.md §1.3, Q5: "four or five tiers, defaulted per behaviour kind"). Five tiers, +// numbered so the lowest number is fed first -- PowerBus's allocation pass walks 0..Count-1 in order. Naming +// them here, once, means IPowerConsumer.DefaultPowerTier implementations read as a sentence ("Radiator is +// Critical") instead of a bare integer repeated eight times. +// +// Assignment, per behaviour kind, and why: +// - Critical: Radiator. This game has no dedicated life-support behaviour, and heat is the closest thing to +// one -- a starved radiator does not just fail itself, it cascades into wear and eventual shutdown across +// every other item on the hull (EquippedItem.UpdatePerformance). Feed it first or lose the rest anyway. +// - High: Shield. Hull survival the player is actively trading power for; not a life-support constant, so it +// sits below Radiator rather than beside it. +// - Medium: Thruster, AetherDrive. Mobility -- needed to hold position, evade, or disengage, but a ship that +// loses thrust for a tick under brownout is inconvenienced, not dead the way an overheating hull is. +// - Low: ConstantWeapon, InstantWeapon. Offense. The ruling's own framing ("low-priority subsystems starve +// first") names weapons as the default example of what a reactor throttle should sacrifice first. +// - Utility: Sensor, EnergyDraw. Everything else, including the generic/unclassified draw -- an item that +// declares power use without asking for a specific tier should not accidentally outrank a named priority. +// +// A tier is a stored player choice once assigned (EquippableItem.PowerTier), not a derivation the bus repeats +// every tick (§1.3 "Derived state: nothing"). These defaults are read exactly once, in EquippedItem's +// constructor, to seed that stored field the first time an item without a chosen tier gets equipped. +public static class PowerTiers +{ + public const int Critical = 0; + public const int High = 1; + public const int Medium = 2; + public const int Low = 3; + public const int Utility = 4; + + public const int Count = 5; + + // EquippableItem.PowerTier's sentinel for "the player has not chosen one and this item has never been + // equipped yet" -- distinct from 0 (Critical), which is a real, meaningful choice. + public const int Unassigned = -1; +} diff --git a/Assets/Scripts/ServerShared/PowerTiers.cs.meta b/Assets/Scripts/ServerShared/PowerTiers.cs.meta new file mode 100644 index 000000000..b3d61cc80 --- /dev/null +++ b/Assets/Scripts/ServerShared/PowerTiers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd20d57dee4a44fa84660631a9c4f5c1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/tests/Aetheria.Shared.Tests/PowerTierTests.cs b/tests/Aetheria.Shared.Tests/PowerTierTests.cs new file mode 100644 index 000000000..85605c61c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/PowerTierTests.cs @@ -0,0 +1,224 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; +using CultMath; +using GameCult.Caching; + +// Cut 5 (docs/stats-and-power-cut.md §1.3): replaces PowerBus's single shared GrantRatio with priority tiers +// (PowerTiers.cs). This file pins Cut 5's own verification bullets plus the "rules worth pinning" the cut brief +// names: critical fed in full while a lower tier starves; two items in one tier rationed proportionally +// regardless of equip order; a tier with no demand passes its share down; reactor throttling changes which +// tiers starve; and a tier boundary does not leak. Each rule has a matching mutation in +// tests/mutation_tests_stats_power_cut5.py. +// +// Fixture shape mirrors PowerBusTests.OpenCatalog/BuildShip (see its comments for why: a 3x3 interior hull, wide +// heat bounds, a Reactor whose Charge each test sets directly). EquipDrain here takes an explicit tier so a test +// can put two Drains in different tiers without waiting on -- or fighting -- EnergyDraw's own kind default +// (PowerTiers.Utility for both), which would otherwise put every Drain in this fixture in the same tier. +public sealed class PowerTierTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-powertier-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public PowerTierTests() => 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 }; + + 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) + } } + }); + cache.FlushAsync().Wait(); + return cache; + } + + private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design) => new EquippableItem + { + Data = cache.RefOf(design), + Durability = design is EquippableItemData equippable ? equippable.Durability : 0, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(design), Origin = new Attributed(), Quality = .5f, Roles = new System.Collections.Generic.List() }) + }; + + 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("Skiff")); + var ship = new Ship(items, zone, hull, new EntitySettings()); + + var reactorData = cache.GetByName("Reactor"); + ((ReactorData) reactorData.Behaviors[0]).Charge = Constant(reactorCharge); + Assert.True(ship.TryEquip(Mint(cache, items, reactorData))); + + zone.Entities.Add(ship); + ship.Activate(); + + var reactor = ship.GetBehavior(); + ship.Update(0f); + return (ship, items, reactor); + } + + // Every Drain needs its own catalog record and PerformanceStat instance (PowerBusTests.EquipDrain's own + // comment explains why: shared resolver entries keyed on the record would otherwise let two Drains fight + // over one mutated rate). The tier is set on the minted unit BEFORE equipping it, so EquippedItem's + // constructor -- which only ever seeds a kind default onto PowerTiers.Unassigned -- never overwrites it; + // this is exactly the "player choice, not a derivation" path §1.3 describes, just exercised directly instead + // of through a schematic-UI click. + private EquippedItem EquipDrain(CultCache cache, Ship ship, float rate, int tier) + { + var perItemData = cache.Upsert(new GearData + { + Name = "Drain " + Guid.NewGuid(), Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10, + MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400, + Behaviors = { new EnergyDrawData { EnergyDraw = Constant(rate), PerSecond = true } } + }); + cache.FlushAsync().Wait(); + ship.Deactivate(); + var unit = Mint(cache, ship.ItemManager, cache.Get(perItemData)); + unit.PowerTier = tier; + Assert.True(ship.TryEquip(unit)); + ship.Activate(); + return ship.Equipment.Last(); + } + + // --- Cut 5 verification bullet 1 / "rules worth pinning" #1: "with generation short of total demand, tier 0 + // --- is satisfied in full before tier 1 receives anything." Generation (30) covers Critical's own demand + // --- (30) exactly, leaving nothing at all for Utility (50) -- the map's own "starves first" framing, pinned + // --- at its sharpest: full satisfaction for the fed tier, total starvation for the other. --- + [Fact] + public void CriticalTierIsFedInFullWhileLowerTierStarves() + { + using var cache = OpenCatalog(); + var (ship, _, _) = BuildShip(cache, reactorCharge: 30); + var critical = EquipDrain(cache, ship, rate: 30, tier: PowerTiers.Critical); + var utility = EquipDrain(cache, ship, rate: 50, tier: PowerTiers.Utility); + + ship.Update(1f); + + Assert.Equal(1f, critical.PowerSupply, 3); + Assert.Equal(0f, utility.PowerSupply, 3); + Assert.Equal(1f, ship.PowerBus.TierGrantRatio[PowerTiers.Critical], 3); + Assert.Equal(0f, ship.PowerBus.TierGrantRatio[PowerTiers.Utility], 3); + } + + // --- "Rules worth pinning" #2: "two items in one tier are rationed proportionally regardless of equip + // --- order." Two Medium consumers, unequal requests (20 and 40), generation covering half the tier's total + // --- demand (30 of 60): both must land at the same .5 ratio, and their absolute grants (10 and 20) must + // --- still be proportional to their own requests, not equal to each other. --- + [Fact] + public void TwoConsumersInOneTierAreRationedProportionally() + { + using var cache = OpenCatalog(); + var (ship, _, _) = BuildShip(cache, reactorCharge: 30); + var small = EquipDrain(cache, ship, rate: 20, tier: PowerTiers.Medium); + var large = EquipDrain(cache, ship, rate: 40, tier: PowerTiers.Medium); + + ship.Update(1f); + + Assert.Equal(.5f, small.PowerSupply, 3); + Assert.Equal(.5f, large.PowerSupply, 3); + Assert.Equal(10f, 20f * small.PowerSupply, 3); // the small request's absolute grant: half of 20 + Assert.Equal(20f, 40f * large.PowerSupply, 3); // the large request's absolute grant: half of 40, not equal to the small one's + } + + // --- "Rules worth pinning" #3: "a tier with no demand passes its share down." Only a Utility consumer is + // --- equipped -- Critical, High, Medium and Low all sit at zero demand -- under a shortfall (generation 10 + // --- against a request of 40). If an empty tier silently swallowed its share instead of passing it on, this + // --- ratio would come out far below the true .25 the single active tier is owed. --- + [Fact] + public void ATierWithNoDemandPassesItsShareDown() + { + using var cache = OpenCatalog(); + var (ship, _, _) = BuildShip(cache, reactorCharge: 10); + var utility = EquipDrain(cache, ship, rate: 40, tier: PowerTiers.Utility); + + ship.Update(1f); + + Assert.Equal(.25f, utility.PowerSupply, 3); + Assert.Equal(.25f, ship.PowerBus.GrantRatio, 3); + for (var tier = 0; tier < PowerTiers.Utility; tier++) + Assert.Equal(1f, ship.PowerBus.TierGrantRatio[tier], 3); // empty tiers read as fully met, never starved + } + + // --- "Rules worth pinning" #4: "reactor throttling changes what is available and therefore which tiers + // --- starve." Same two-tier loadout (Critical 30, Utility 50) at two different reactor charges: a weak + // --- reactor starves Utility entirely (as CriticalTierIsFedInFullWhileLowerTierStarves already pins); a + // --- strong one (80, covering both) starves nothing. The player's own reactor-tier choice is what moves a + // --- subsystem across that line, exactly the ruling's "reactor throttling is a player choice." --- + [Fact] + public void ReactorThrottlingChangesWhichTiersStarve() + { + using var cache = OpenCatalog(); + var (ship, _, _) = BuildShip(cache, reactorCharge: 80); + var critical = EquipDrain(cache, ship, rate: 30, tier: PowerTiers.Critical); + var utility = EquipDrain(cache, ship, rate: 50, tier: PowerTiers.Utility); + + ship.Update(1f); + + Assert.Equal(1f, critical.PowerSupply, 3); + Assert.Equal(1f, utility.PowerSupply, 3); // unlike the 30-charge case, generation now covers both in full + } + + // --- "Rules worth pinning" #5: "a tier boundary does not leak." Critical alone outweighs generation (demand + // --- 100 against 40), so Critical itself is starved (.4). A lower tier must still receive exactly zero -- + // --- not some leftover sliver reasoned from Critical's own shortfall -- because remaining hits 0 once + // --- Critical's grant is committed, before Utility is ever considered. --- + [Fact] + public void LowerTierGetsExactlyZeroWhenAHigherTierAloneStarves() + { + using var cache = OpenCatalog(); + var (ship, _, _) = BuildShip(cache, reactorCharge: 40); + var critical = EquipDrain(cache, ship, rate: 100, tier: PowerTiers.Critical); + var utility = EquipDrain(cache, ship, rate: 50, tier: PowerTiers.Utility); + + ship.Update(1f); + + Assert.Equal(.4f, critical.PowerSupply, 3); + Assert.Equal(0f, utility.PowerSupply, 3); + } + + // --- Cut 5's own verification bullet: "a tier change on an equipped item takes effect on the next tick with + // --- no re-equip." §1.3 calls the tier "a stored player choice, not a derivation" -- this proves the store + // --- is live, not latched at equip time. A fixed Critical consumer (5) and generation of 15 leave 10 for a + // --- Utility mover requesting 20 (.5 ratio); moving the mover into Critical alongside the fixed one changes + // --- the tier's own total demand to 25 against the same 15 supply (.6 ratio) on the very next Step, with no + // --- unequip/re-equip round trip -- proof the read is live, not a value latched once at equip time. + [Fact] + public void ATierChangeOnAnEquippedItemTakesEffectNextTickWithNoReEquip() + { + using var cache = OpenCatalog(); + var (ship, _, _) = BuildShip(cache, reactorCharge: 15); + EquipDrain(cache, ship, rate: 5, tier: PowerTiers.Critical); + var mover = EquipDrain(cache, ship, rate: 20, tier: PowerTiers.Utility); + + ship.Update(1f); + Assert.Equal(.5f, mover.PowerSupply, 3); + + mover.EquippableItem.PowerTier = PowerTiers.Critical; + ship.Update(1f); + + Assert.Equal(.6f, mover.PowerSupply, 3); + } +} diff --git a/tests/mutation_tests_stats_power_cut5.py b/tests/mutation_tests_stats_power_cut5.py new file mode 100644 index 000000000..c554e3e3b --- /dev/null +++ b/tests/mutation_tests_stats_power_cut5.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Mutation tests for docs/stats-and-power-cut.md Cut 5 (priority tiers). + +Cut 5 replaces PowerBus's single shared GrantRatio with priority tiers (PowerTiers.cs): critical is fed in full +before the next tier sees anything, each following tier divides what remains, and a tier is a stored player +choice (EquippableItem.PowerTier) rather than something the bus derives every tick. This script mutates each +rule's own line of code and asserts the named test in PowerTierTests.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_cut5.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" + + +@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/PowerBus.cs", + anchor=" if (demand <= 1e-4f) { ratios[tier] = 1f; continue; }", + mutated=" if (demand <= 1e-4f) { ratios[tier] = 1f; continue; }", + test="PowerTierTests.CriticalTierIsFedInFullWhileLowerTierStarves", + expect="green", + ), + + # --- Cut 5's headline rule: critical must be satisfied in full before the next tier receives anything. + # --- Walking tiers in descending order instead of ascending feeds Utility first, so the fixed generation + # --- that exactly covers Critical's own demand gets spent on Utility instead, starving Critical -- the + # --- opposite of the ruling ("critical is fed first"). --- + Mutation( + rule="tiers must be walked lowest-number (highest priority) first", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" for (var tier = 0; tier < PowerTiers.Count; tier++)", + mutated=" for (var tier = PowerTiers.Count - 1; tier >= 0; tier--)", + test="PowerTierTests.CriticalTierIsFedInFullWhileLowerTierStarves", + expect="red", + ), + + # --- A satisfied tier must commit what it took, so a lower tier can never see it again. Skipping the + # --- subtraction lets every tier see the SAME remaining pool -- Utility would compute against the full 30, + # --- not the 0 left after Critical, so it would stop reading as fully starved. --- + Mutation( + rule="a fed tier must commit its grant against remaining, or a lower tier could see it twice", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" remaining -= grant;", + mutated=" // remaining -= grant;", + test="PowerTierTests.CriticalTierIsFedInFullWhileLowerTierStarves", + expect="red", + ), + + # --- Within a tier, every consumer must ration by the SAME fraction of its OWN request -- that is what + # --- makes two unequal requests divide proportionally instead of splitting the tier's grant evenly per + # --- consumer regardless of how much each asked for. --- + Mutation( + rule="within a tier, the ratio must be grant/demand (proportional), not an even per-consumer split", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" ratios[tier] = saturate(grant / demand);", + mutated=" ratios[tier] = saturate(grant / tierDemand.Length);", + test="PowerTierTests.TwoConsumersInOneTierAreRationedProportionally", + expect="red", + ), + + # --- An empty tier must read as fully met (ratio 1, remaining untouched) so its share passes straight to + # --- the next tier down. Forcing it to 0 instead makes an unused tier look starved and -- because nothing + # --- reduces remaining for a 0-demand tier either way -- has no effect on the real consumer, but the + # --- assertion on the empty tiers' own ratio catches the wrong value directly. --- + Mutation( + rule="a tier with no demand must read as fully met (1f), not starved (0f)", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" if (demand <= 1e-4f) { ratios[tier] = 1f; continue; }", + mutated=" if (demand <= 1e-4f) { ratios[tier] = 0f; continue; }", + test="PowerTierTests.ATierWithNoDemandPassesItsShareDown", + expect="red", + ), + + # --- TotalGrant is the ceiling tiering allocates -- it must still reflect what generation and stored charge + # --- can actually cover, not the raw total request. Feeding the allocator TotalDemand instead (pretending + # --- supply always covers everything) hands Utility the untouched 80 instead of the 0 left after Critical's + # --- own 30 is committed, so it reads as fully fed instead of starved. --- + Mutation( + rule="tiering must allocate against TotalGrant (what supply covers), not TotalDemand (what was asked)", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" var remaining = TotalGrant;", + mutated=" var remaining = TotalDemand;", + test="PowerTierTests.CriticalTierIsFedInFullWhileLowerTierStarves", + expect="red", + ), + + # --- The boundary rule itself: once a higher tier's own shortfall has consumed all of remaining, a lower + # --- tier must see 0, not some leftover computed from the higher tier's unmet demand. Handing every tier + # --- the ORIGINAL TotalGrant instead of the shrinking remaining pool would let Utility compute its own + # --- ratio against the full grant as if Critical had never been served first -- exactly the leak §1.3 + # --- forbids. --- + Mutation( + rule="each tier must divide what is actually left (remaining), not the original total grant again", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" var grant = min(demand, remaining);", + mutated=" var grant = min(demand, TotalGrant);", + test="PowerTierTests.LowerTierGetsExactlyZeroWhenAHigherTierAloneStarves", + expect="red", + ), + + # --- The tier must be read fresh from the stored field every Step, not cached at equip time -- otherwise a + # --- player's tier change on the schematic UI would need an unequip/re-equip round trip to take effect, + # --- which the map's own verification bullet rules out. --- + Mutation( + rule="the bus must read the item's CURRENT stored PowerTier every Step, not one captured once at equip", + file="Assets/Scripts/ServerShared/PowerBus.cs", + anchor=" var tier = item.EquippableItem.PowerTier;", + mutated=" var tier = consumer.DefaultPowerTier;", + test="PowerTierTests.ATierChangeOnAnEquippedItemTakesEffectNextTickWithNoReEquip", + expect="red", + ), + + # --- EquippedItem's constructor must seed a kind default only once, the first time a unit is equipped + # --- (PowerTiers.Unassigned) -- never re-seeding it on every equip is what makes the tier a genuinely stored + # --- choice instead of one silently reset back to the kind default whenever a unit changes hands. Removing + # --- the guard reassigns Utility's own default even after a mutating test has moved it to Critical. + Mutation( + rule="the kind default must only be seeded when PowerTier is still Unassigned, never re-seeded", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" if (EquippableItem.PowerTier == PowerTiers.Unassigned)\n {\n var consumerTiers = Behaviors.OfType().Select(c => c.DefaultPowerTier).ToArray();\n if (consumerTiers.Length > 0)\n EquippableItem.PowerTier = consumerTiers.Min();\n }", + mutated=" {\n var consumerTiers = Behaviors.OfType().Select(c => c.DefaultPowerTier).ToArray();\n if (consumerTiers.Length > 0)\n EquippableItem.PowerTier = consumerTiers.Min();\n }", + test="PowerTierTests.ATierChangeOnAnEquippedItemTakesEffectNextTickWithNoReEquip", + 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())