From 39b6d28f3a3212d9e728ad06e603bb479f79df84 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 6 Oct 2026 19:30:31 +0200 Subject: [PATCH] StationServices: one engine-free owner for sell price, repair cost and the sale and repair commits Settings gain SellFraction, RepairFraction and StartingCredits. A sale pays the price scaled by condition and moves the item into a station bay or refuses with everything unchanged; a repair restores every durability and charges the wear, or refuses when short. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/Settings.cs | 5 + .../Scripts/ServerShared/StationServices.cs | 82 ++++++++ .../StationServicesTests.cs | 178 ++++++++++++++++++ 3 files changed, 265 insertions(+) create mode 100644 Assets/Scripts/ServerShared/StationServices.cs create mode 100644 tests/Aetheria.Shared.Tests/StationServicesTests.cs diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 67de2f0aa..cc7de7652 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -161,6 +161,11 @@ public class GameplaySettings public EntitySettings DefaultEntitySettings; public RarityTier[] Tiers; public ExponentialLerp QualityPriceModifier; + // What a station pays for goods, as a fraction of their price, scaled further by the item's condition. + public float SellFraction = .5f; + // What a station charges to restore worn gear, as a fraction of the price of the wear. + public float RepairFraction = .25f; + public int StartingCredits = 15000000; public float DurabilityQualityExponent = 2; public float DurabilityQualityMin = 2; public float DurabilityQualityMax = .25f; diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs new file mode 100644 index 000000000..b6b363dde --- /dev/null +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +// What a station pays for goods and charges to mend gear. The one owner of the sell price, the repair cost, and the +// two commits that move goods or restore durability against the run's credits; TradeMenu shows these numbers and +// decides none of them. It holds no Unity type. Credits are the caller's: a refusal leaves them, the cargo and the +// durabilities exactly as they were. +public static class StationServices +{ + // What the station pays for the item: its price, scaled by SellFraction and by its condition. A commodity has no + // wear, so it sells at the fraction alone; a simple commodity's price is per unit. + public static int SellPrice(ItemManager items, ItemInstance item) + { + var fraction = (double) items.GameplaySettings.SellFraction; + switch (item) + { + case CraftedItemInstance crafted: + return (int) Math.Floor(items.GetPrice(crafted) * fraction * Condition(items, crafted)); + case SimpleCommodity commodity: + return (int) Math.Floor((long) items.GetData(commodity).Price * commodity.Quantity * fraction); + default: + throw new ArgumentException($"{item?.GetType().Name ?? "null"} has no sell price.", nameof(item)); + } + } + + // What the station charges to restore the entity's hull and every item it carries to design durability: each + // piece's share of its price in proportion to its wear, scaled by RepairFraction, rounded up. + public static int RepairCost(ItemManager items, Entity entity) + { + long total = 0; + foreach (var gear in Gear(entity)) total += RepairShare(items, gear); + return (int) Math.Min(total, int.MaxValue); + } + + // The sale: the item leaves the bay for one of the station's cargo bays and the station pays SellPrice. False, + // with the item in its bay and the credits unchanged, when no station bay can take it. + public static bool TrySell(EquippedCargoBay from, Entity station, ItemInstance item, ref int credits) + { + var price = SellPrice(station.ItemManager, item); + var moved = item is SimpleCommodity commodity + ? station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, commodity.Quantity)) + : station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item)); + if (!moved) return false; + credits += price; + return true; + } + + // The repair: every durability goes back to design and the station charges RepairCost. False, with nothing + // restored, when the credits fall short. + public static bool TryRepair(Entity entity, ref int credits) + { + var items = entity.ItemManager; + var cost = RepairCost(items, entity); + if (cost > credits) return false; + foreach (var gear in Gear(entity)) + if (items.GetData(gear) is EquippableItemData design && design.Durability > 0) + gear.Durability = design.Durability; + credits -= cost; + return true; + } + + // Equipment holds the hull itself, so the hull is in the sum once. + private static IEnumerable Gear(Entity entity) => + entity.Equipment.Select(equipped => equipped.EquippableItem) + .Concat(entity.CargoBays.Select(bay => bay.EquippableItem)) + .Concat(entity.DockingBays.Select(bay => bay.EquippableItem)); + + // Instance durability over the design's, for gear that wears; everything else is as good as new. + private static double Condition(ItemManager items, CraftedItemInstance item) + { + if (!(item is EquippableItem gear) || !(items.GetData(gear) is EquippableItemData design) || design.Durability <= 0) + return 1; + return Math.Max(0, Math.Min(1, gear.Durability / (double) design.Durability)); + } + + private static long RepairShare(ItemManager items, EquippableItem gear) + { + var worn = 1 - Condition(items, gear); + return (long) Math.Ceiling(worn * items.GetPrice(gear) * items.GameplaySettings.RepairFraction); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs new file mode 100644 index 000000000..1685af834 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// What a station pays and charges, and the commits that move goods and credits. The price rules are pinned against the +// authored gameplay settings, so the defaults a Settings.asset without the new fields keeps are the ones tested. +public sealed class StationServicesTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-stationservices-" + Guid.NewGuid().ToString("N")); + private readonly CultCache _cache; + private readonly ItemManager _items; + private readonly Zone _zone; + + public StationServicesTests() + { + Directory.CreateDirectory(_root); + _cache = AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), catalogWritable: true); + _cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + var shape = new Shape(3, 3); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var hardpoint = new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() }; + _cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Hardpoints = { hardpoint } }); + _cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10 }); + _cache.Upsert(new HullData { Name = "Bare Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10 }); + _cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 400, Durability = 8 }); + _cache.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 90, Durability = 0 }); + var bay = new Shape(4, 4); + foreach (var cell in bay.AllCoordinates) bay[cell] = true; + _cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); + _cache.Upsert(new SimpleCommodityData { Name = "Ore", Shape = new Shape(), Price = 7, MaxStack = 100 }); + _cache.FlushAsync().Wait(); + + var settings = AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"); + _items = new ItemManager(_cache, new ProvenanceLedger(), settings, _ => { }); + _zone = new Zone(_items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + } + + public void Dispose() + { + _cache.Dispose(); + Directory.Delete(_root, true); + } + + private EquippableItem Mint(string design, float? durability = null) + { + var data = _cache.GetByName(design); + return new EquippableItem + { + Data = _cache.RefOf(data), + Durability = durability ?? data.Durability, + Lot = _items.Lots.Add(new Lot { Design = _cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + + private SimpleCommodity Ore(int quantity) => new SimpleCommodity { Data = _cache.RefOf(_cache.GetByName("Ore")), Quantity = quantity }; + + // A ship with a cargo bay. + private Ship Ship(float? hullDurability = null) + { + var ship = new Ship(_items, _zone, Mint("Skiff", hullDurability), new EntitySettings()); + Assert.True(ship.TryEquip(Mint("Crate"), new int2(1, 1))); + return ship; + } + + // A station whose one cargo bay can take the goods, or one with no cargo bay at all. + private OrbitalEntity Station(bool withBay = true) + { + var station = new OrbitalEntity(_items, _zone, Mint(withBay ? "Hub" : "Bare Hub"), default, new EntitySettings()); + if (withBay) Assert.True(station.TryEquip(Mint("Crate"), new int2(1, 1))); + return station; + } + + [Fact] + public void SettingsDefaultsAreHalfAndAQuarter() + { + Assert.Equal(.5f, _items.GameplaySettings.SellFraction); + Assert.Equal(.25f, _items.GameplaySettings.RepairFraction); + Assert.Equal(15000000, _items.GameplaySettings.StartingCredits); + } + + [Fact] + public void SellPrice_scales_with_condition() + { + var price = _items.GetPrice(Mint("Gun")); + Assert.True(price > 100, "the fixture's gun must have a price large enough to show a half"); + Assert.Equal((int) Math.Floor(price * .5), StationServices.SellPrice(_items, Mint("Gun"))); + Assert.Equal((int) Math.Floor(price * .25), StationServices.SellPrice(_items, Mint("Gun", 4))); + Assert.Equal(0, StationServices.SellPrice(_items, Mint("Gun", 0))); + + // A design with no durability does not wear, so it sells as new however its instance reads. + Assert.Equal((int) Math.Floor(_items.GetPrice(Mint("Lamp")) * .5), StationServices.SellPrice(_items, Mint("Lamp", 0))); + // Past design durability is no better than new. + Assert.Equal(StationServices.SellPrice(_items, Mint("Gun")), StationServices.SellPrice(_items, Mint("Gun", 80))); + // A commodity has no wear: its price per unit times the quantity, at the fraction. + Assert.Equal(35, StationServices.SellPrice(_items, Ore(10))); + Assert.Equal(0, StationServices.SellPrice(_items, Ore(1))); + } + + [Fact] + public void TrySell_moves_and_pays_or_refuses() + { + var ship = Ship(); + var from = ship.CargoBays.Single(); + var gun = Mint("Gun", 4); + var ore = Ore(10); + Assert.True(from.TryStore(gun)); + Assert.True(from.TryStore(ore)); + var station = Station(); + var credits = 1000; + + Assert.True(StationServices.TrySell(from, station, gun, ref credits)); + Assert.Equal(1000 + StationServices.SellPrice(_items, Mint("Gun", 4)), credits); + Assert.DoesNotContain(gun, from.Cargo.Keys); + Assert.Contains(gun, station.CargoBays.Single().Cargo.Keys); + + credits = 1000; + Assert.True(StationServices.TrySell(from, station, ore, ref credits)); + Assert.Equal(1035, credits); + Assert.Empty(from.Cargo.Keys.OfType()); + Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); + + // A station with nowhere to put it takes nothing and pays nothing. + var other = Mint("Gun"); + Assert.True(from.TryStore(other)); + var packed = from.Cargo.Count; + credits = 1000; + Assert.False(StationServices.TrySell(from, Station(withBay: false), other, ref credits)); + Assert.Equal(1000, credits); + Assert.Equal(packed, from.Cargo.Count); + Assert.Contains(other, from.Cargo.Keys); + } + + [Fact] + public void Repair_restores_and_charges() + { + var whole = Ship(); + Assert.True(whole.TryEquip(Mint("Gun"))); + Assert.Equal(0, StationServices.RepairCost(_items, whole)); + var credits = 50; + Assert.True(StationServices.TryRepair(whole, ref credits)); + Assert.Equal(50, credits); + + var ship = Ship(hullDurability: 5); + Assert.True(ship.TryEquip(Mint("Gun", 2))); + var cost = StationServices.RepairCost(_items, ship); + var hull = (int) Math.Ceiling(.5 * _items.GetPrice(ship.Hull) * .25); + var gun = (int) Math.Ceiling(.75 * _items.GetPrice(Mint("Gun")) * .25); + Assert.Equal(hull + gun, cost); + + var shortOfCost = cost - 1; + Assert.False(StationServices.TryRepair(ship, ref shortOfCost)); + Assert.Equal(cost - 1, shortOfCost); + Assert.Equal(5, ship.Hull.Durability); + Assert.Equal(2, ship.Equipment.Single(e => e.EquippableItem != ship.Hull).EquippableItem.Durability); + + var exact = cost; + Assert.True(StationServices.TryRepair(ship, ref exact)); + Assert.Equal(0, exact); + Assert.Equal(10, ship.Hull.Durability); + Assert.Equal(8, ship.Equipment.Single(e => e.EquippableItem != ship.Hull).EquippableItem.Durability); + Assert.Equal(0, StationServices.RepairCost(_items, ship)); + } + + [Fact] + public void Repair_counts_cargo_bays_as_gear() + { + var ship = Ship(); + ship.CargoBays.Single().EquippableItem.Durability = 1; + Assert.True(StationServices.RepairCost(_items, ship) > 0, "a worn cargo bay costs to mend"); + var credits = 1000000; + Assert.True(StationServices.TryRepair(ship, ref credits)); + Assert.Equal(4, ship.CargoBays.Single().EquippableItem.Durability); + } +}