diff --git a/Assets/Scripts/ServerShared/AetheriaStores.cs b/Assets/Scripts/ServerShared/AetheriaStores.cs index 7c93ba979..9e4084f88 100644 --- a/Assets/Scripts/ServerShared/AetheriaStores.cs +++ b/Assets/Scripts/ServerShared/AetheriaStores.cs @@ -8,7 +8,7 @@ using GameCult.Caching.MessagePack; public static class AetheriaStores { public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData), typeof(ProvinceData), typeof(VerseGrammar), typeof(VerseVerb), typeof(StationKindData), typeof(RecipeData), typeof(OutsideMarketData) }; - public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger) }; + public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger), typeof(HaulOrderData) }; public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) }; // Attaches (hydrates) the catalog read-only unless catalogWritable, then the run and player stores when given. diff --git a/Assets/Scripts/ServerShared/EconomyChecks.cs b/Assets/Scripts/ServerShared/EconomyChecks.cs index 3fe389321..13b72d1c3 100644 --- a/Assets/Scripts/ServerShared/EconomyChecks.cs +++ b/Assets/Scripts/ServerShared/EconomyChecks.cs @@ -265,7 +265,7 @@ public static class EconomyChecks var item = catalog.Get(listed); if (!listed.IsSet()) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] is unset."); else if (item == null) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] names no item this catalog holds."); - else if (!StationKinds.IsRecipeFacility(item)) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] '{item.Name}' is not a recipe facility."); + else if (!StationKinds.IsRecipeFacility(item) && !(item is SiloData)) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] '{item.Name}' is not a recipe facility or a silo."); } foreach (var gear in catalog.GetAll().Select(gear => (Key: catalog.RefOf(gear).Key.Value, Gear: gear)).OrderBy(pair => pair.Key, StringComparer.Ordinal)) if (gear.Gear.Behaviors != null && gear.Gear.Behaviors.Any(behavior => behavior is FacilityData) && gear.Gear.HardpointType != HardpointType.Facility) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 2c2cfefdb..2a3198814 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1685,29 +1685,28 @@ public abstract class Entity // The one seat of hardpoint gear's rotation, before EquippedItem's ctor reads it. if (hardpoint != null) item.Rotation = hardpoint.Rotation; + // A bay is decided by its type before its hardpoint: a docking bay or cargo bay, a silo among them, is a bay whether it + // sits free (Tool) or on a row (a silo on its Facility row); then Tool gear, then hardpoint gear. EquippedItem equippedItem; - if (itemData.HardpointType == HardpointType.Tool) + if (itemData is CargoBayData) { - if(itemData is CargoBayData) + if (itemData is DockingBayData) { - if (itemData is DockingBayData) - { - equippedItem = new EquippedDockingBay(ItemManager, item, hullCoord, this, $"{Name} Docking Bay {DockingBays.Count + 1}"); - DockingBays.Add((EquippedDockingBay) equippedItem); - } - else - { - equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, this, $"{Name} Cargo Bay {CargoBays.Count + 1}"); - CargoBays.Add((EquippedCargoBay) equippedItem); - CargoChanged(); - } + equippedItem = new EquippedDockingBay(ItemManager, item, hullCoord, this, $"{Name} Docking Bay {DockingBays.Count + 1}"); + DockingBays.Add((EquippedDockingBay) equippedItem); } else { - equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, null); - Equipment.Add(equippedItem); + equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, this, $"{Name} Cargo Bay {CargoBays.Count + 1}", hardpoint); + CargoBays.Add((EquippedCargoBay) equippedItem); + CargoChanged(); } } + else if (itemData.HardpointType == HardpointType.Tool) + { + equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, null); + Equipment.Add(equippedItem); + } else { equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, hardpoint); @@ -2443,7 +2442,7 @@ public class EquippedCargoBay : EquippedItem } } - public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name) : base(itemManager, item, position, entity, null) + public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name, HardpointData hardpoint = null) : base(itemManager, item, position, entity, hardpoint) { Data = ItemManager.GetData(EquippableItem) as CargoBayData; Name = name; @@ -2457,6 +2456,8 @@ public class EquippedCargoBay : EquippedItem // Check whether the given item will fit when its origin is placed at the given coordinate public bool ItemFits(ItemInstance item, int2 cargoCoord) { + // A silo holds bulk only: gear, consumables and crafted sales never land in it. + if (Data is SiloData && !(item is ICommodityStack)) return false; var itemData = ItemManager.GetData(item); // Check every cell of the item's shape foreach (var i in itemData.Shape.Coordinates) diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index 792b9029c..6d2893cb8 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -488,6 +488,15 @@ public class DockingBayData : CargoBayData public int2 MaxSize; } +// A silo: bulk storage seated on a Facility row (idea stations-gear-map.one-mount-for-station-gear). It is a cargo bay that holds +// commodity stacks only, so gear, consumables and crafted sales never land in it; what a station buys for one is its haul +// orders' goods (StationWants). +[CultDocument("aetheria.silodata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class SiloData : CargoBayData +{ + [IgnoreMember] public override HardpointType HardpointType => HardpointType.Facility; +} + [CultDocument("aetheria.weaponitemdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class WeaponItemData : GearData { diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index 8f48bf033..5bec63b34 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -21,6 +21,10 @@ public class LoadoutGenerator // station draws 1 to the maximum. public const float StationConsumableChance = .25f; public const int StationConsumableUnits = 2; + // The share of a station's stock bay its generated gear may fill; the rest stays free for what the station buys (rulings + // no-market-absorption, station-intake-few-sorties). A first value of a sim-tuned knob (economy-numbers-are-sim-tuned-knobs): + // follow-up economy-balance-station-drain tunes it. + public const float StationStockShare = .5f; public const float ShipConsumableChance = .1f; public const int ShipConsumableUnits = 1; @@ -140,14 +144,21 @@ public class LoadoutGenerator // offer nothing is drawn here, so the gear draws are exactly what they were. StockConsumables(entity, StationConsumableChance, StationConsumableUnits); - var cargo = entity.CargoBays.First(); + // The gear stock goes to the first bay that is not a silo and stops short of StationStockShare of its cells, so a + // station's hold keeps room for what it buys (ruling no-market-absorption). All sixteen picks are still drawn, so no + // random stream moves; only storing stops. + var cargo = entity.CargoBays.First(bay => !(bay.Data is SiloData)); + var stockCells = (int) (cargo.Data.InteriorShape.Coordinates.Length * StationStockShare); + var stocked = cargo.Data.InteriorShape.Coordinates.Count(cell => cargo.Occupancy[cell.x, cell.y] != null); var inventory = RandomProducts(16, 1, data => !(data is HullData hull && hull.HullType != HullType.Ship) && !(data is CargoBayData)) .OrderByDescending(entry => entry.design.Shape.Coordinates.Length); foreach (var entry in inventory) { var instance = ItemManager.CreateInstance(entry.product); - cargo.TryStore(instance); + var cells = entry.design.Shape.Coordinates.Length; + if (stocked + cells > stockCells) continue; + if (cargo.TryStore(instance)) stocked += cells; } entity.CanTow = hullData.CanTow; @@ -441,7 +452,7 @@ public class LoadoutGenerator var emptyShape = entity.UnoccupiedSpace; var (cargoProduct, cargoData) = RandomProduct(3, item => - !(item is DockingBayData) && + !(item is DockingBayData) && !(item is SiloData) && item.Shape.FitsWithin(emptyShape, out _, out _), required: true); if (cargoData == null) throw new InvalidLoadoutException("No compatible cargo bay found for entity!"); diff --git a/Assets/Scripts/ServerShared/Production.cs b/Assets/Scripts/ServerShared/Production.cs index 04c54866b..189f5ceb2 100644 --- a/Assets/Scripts/ServerShared/Production.cs +++ b/Assets/Scripts/ServerShared/Production.cs @@ -47,6 +47,14 @@ public static class Production public static IReadOnlyList RunList(CultCache catalog, CultRecordKey facilityDesign) => Recipes.RunOn(catalog, facilityDesign).Where(recipe => Runs(catalog, recipe)).ToArray(); + // The designs Take can take for the recipe: Inputs, Upkeep, and the fillers of each role slot, in that order, each once. Beside + // Take, which it must never disagree with: a good a recipe draws is a good its facility's station wants (StationWants). + public static IReadOnlyList Draws(CultCache catalog, RecipeData recipe) => + recipe.Inputs.Select(input => input.Commodity.Key) + .Concat(recipe.Upkeep.Select(upkeep => upkeep.Commodity.Key)) + .Concat(Recipes.RoleInputsOf(catalog, recipe).SelectMany(role => Recipes.Fillers(catalog, role.Name))) + .Distinct().ToArray(); + // The units one cycle of the recipe takes from the hold, summed per design: Inputs, then Upkeep, then each role slot filled // greedily across Recipes.Fillers order. Null when the hold is short of any. public static IReadOnlyList<(CultRecordKey design, int units)> Take(CultCache catalog, RecipeData recipe, IProductionHold hold) diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index a39a94578..afb8ccfda 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -260,8 +260,12 @@ public class ZoneStage // once at admission. Neutral writes nothing (the faction rule and grudges decide). Only RunStart builds one. public sealed class ScenarioStage : ZoneStage { + private readonly ItemManager _runItems; + private readonly List<(string id, HaulOrderData order)> _haulOrders = new List<(string, HaulOrderData)>(); + internal ScenarioStage(ItemManager items, Zone arena, string startingHull) : base(items, arena) { + _runItems = items; StartingHull = startingHull; Credits = items.GameplaySettings.StartingCredits; } @@ -301,11 +305,43 @@ public sealed class ScenarioStage : ZoneStage return null; } + // The arena's one station of a kind (what it is for, never its hull); a failure naming the kind when there is none or several. + public OrbitalEntity Station(string kindId) + { + var kind = StationKindData.KeyOf(kindId); + var found = Arena.Entities.OfType().Where(entity => entity.Kind.IsSet() && entity.Kind.Key.Equals(kind)).Take(2).ToArray(); + if (found.Length == 1) return found[0]; + _failures.Add(found.Length == 0 ? $"station {kindId}: the arena holds no station of that kind" : $"station {kindId}: the arena holds more than one station of that kind"); + return null; + } + + // A standing haul order between two of the arena's stations, by their orbits (ruling transit-depots-buy-for-onward-haul). + // Queued here and written only in Admit, so a refused stage writes nothing. + public void HaulOrder(string id, OrbitalEntity from, OrbitalEntity to, IEnumerable> goods, string commitment) + { + if (from == null || to == null) return; // the verb that found them named why + if (!from.OrbitData.IsSet() || !to.OrbitData.IsSet()) + { + _failures.Add($"haul order {id}: a station with no orbit record cannot be a haul order's end"); + return; + } + _haulOrders.Add((id, new HaulOrderData + { + From = new CultRecordRef(from.OrbitData), To = new CultRecordRef(to.OrbitData), + Goods = goods.ToList(), Commitment = commitment + })); + } + // Run start's admission: stock unauthored ammunition, the player, then everything placed. Nothing at admission or // activation reads cargo (ammunition is read when a weapon fires), so stocking is not ordered by admission; it keeps // the run start's order. internal void Admit() { + if (_haulOrders.Count > 0) + _runItems.ItemData.Commit(batch => + { + foreach (var (id, order) in _haulOrders) batch.Upsert(typeof(HaulOrderData), order, HaulOrderData.KeyOf(id)); + }); StockUnauthoredAmmunition(); PlayerShip.IsPlayerShip = true; Arena.Admit(PlayerShip, piloted: false); diff --git a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs index beb86a59e..08c4f28b0 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs @@ -1,4 +1,6 @@ using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; using float2 = CultMath.float2; // The demo: one gate, one region and one boss, with a fixed cast. The Pirates are the protagonist's ostensible @@ -49,5 +51,15 @@ public sealed class DemoTerminus : Scenario foreach (var neutral in Cast.NeutralFactions) galaxy.FactionRelationships[galaxy.ResolveFaction(neutral)] = FactionRelationship.Neutral; stage.Player(stage.Generated("Longinus"), float2.zero); + + // Zenith's silo buys the ores the refinery's gear draws (ruling demo-zenith-ore-depot), by a standing order to the + // refinery; nothing hauls it yet (follow-up ore-haul-run). + var zenith = stage.Station("trade-hub"); + var refinery = stage.Station("processing"); + if (refinery == null) return; + var items = refinery.ItemManager; + var ores = StationWants.Of(refinery).Where(good => FieldKinds.IsOre(items.ItemData, items.ItemData.Get(new CultRecordRef(good)))) + .OrderBy(good => good.Value, System.StringComparer.Ordinal).Select(good => new CultRecordRef(good)); + stage.HaulOrder("demo-terminus-ore", zenith, refinery, ores, "scenario:demo-terminus"); } } diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index baed304c7..26945d364 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -114,14 +114,15 @@ public static class StationServices return true; } - // The sale of a commodity stack (aetheria-living-world:ruling:no-market-absorption): the station's bays take what they - // can hold, the station pays SellPrice for those units alone, and the rest stays in the seller's hold. Sold units are - // moved, never absorbed. + // The sale of a commodity stack: only a good the station wants (StationWants; NotWanted moves nothing). The station's bays + // take what they can hold (aetheria-living-world:ruling:no-market-absorption), the station pays SellPrice for those units + // alone, and the rest stays in the seller's hold with the refusal NoRoom. Sold units are moved, never absorbed. public static SaleResult TrySellPart(EquippedCargoBay from, Entity station, ICommodityStack stack, ref int credits) { var item = (ItemInstance) stack; var offered = stack.Quantity; if (!from.Cargo.ContainsKey(item)) return new SaleResult(0, offered, SaleRefusal.None); + if (!StationWants.Of(station).Contains(item.Data.Key)) return new SaleResult(0, offered, SaleRefusal.NotWanted); var sold = 0; var remaining = offered; while (remaining > 0) @@ -146,18 +147,25 @@ public static class StationServices private static ItemInstance[] OreStacks(ItemManager items, IEnumerable bays) => bays.SelectMany(bay => bay.Cargo.Keys.OfType().Where(stack => FieldKinds.IsOre(items.ItemData, items.GetData(stack))).Select(stack => (ItemInstance) stack)).ToArray(); - // What the station pays for every ore stack of the bays: the sum of SellPrice over the stacks TrySellOre sells. - public static int OreValue(ItemManager items, IEnumerable bays) => - (int) Math.Min(OreStacks(items, bays).Sum(stack => (long) SellPrice(items, stack)), int.MaxValue); + // What the station would pay for every ore stack of the bays that it wants: the sum of SellPrice over the stacks TrySellOre + // sells. A display value: it ignores the station's room. + public static int OreValue(ItemManager items, IEnumerable bays, Entity station) => + (int) Math.Min(WantedOreStacks(items, bays, station).Sum(stack => (long) SellPrice(items, stack)), int.MaxValue); - // Sells every ore stack of the bays, each through TrySellPart, so the price and the room rule are the single-stack + private static ItemInstance[] WantedOreStacks(ItemManager items, IEnumerable bays, Entity station) + { + var wants = StationWants.Of(station); + return OreStacks(items, bays).Where(stack => wants.Contains(stack.Data.Key)).ToArray(); + } + + // Sells every ore stack of the bays that the station wants, each through TrySellPart, so the price and the room rule are the single-stack // path's. Returns the units sold and offered, with the last refusal. public static SaleResult TrySellOre(IEnumerable bays, Entity station, ref int credits) { var bayList = bays.ToArray(); int sold = 0, offered = 0; var refusal = SaleRefusal.None; - foreach (var stack in OreStacks(station.ItemManager, bayList)) + foreach (var stack in WantedOreStacks(station.ItemManager, bayList, station)) { var from = bayList.First(bay => bay.Cargo.ContainsKey(stack)); var result = TrySellPart(from, station, (ICommodityStack) stack, ref credits); diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs new file mode 100644 index 000000000..4c203387b --- /dev/null +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using MessagePack; +using Newtonsoft.Json; + +// What a station buys (aetheria-living-world:ruling:installed-gear-decides-what-a-station-buys): the goods its installed +// recipe facilities draw, and, when it carries a silo, the goods of the haul orders that start at its orbit +// (ruling transit-depots-buy-for-onward-haul). Derived on every call from the station's gear and the catalog, stored nowhere. +// StationServices.TrySellPart is gated by it and limited by the bays' room. +public static class StationWants +{ + public static IReadOnlyCollection Of(Entity station) + { + var catalog = station.ItemManager.ItemData; + var wants = new HashSet(); + foreach (var equipped in station.Equipment) + { + var design = station.ItemManager.GetData(equipped.EquippableItem); + if (!StationKinds.IsRecipeFacility(design)) continue; + foreach (var recipe in Production.RunList(catalog, catalog.RefOf(design).Key)) + foreach (var draw in Production.Draws(catalog, recipe)) + wants.Add(draw); + } + if (station is OrbitalEntity { OrbitData: var orbit } && orbit.IsSet() && station.CargoBays.Any(bay => bay.Data is SiloData)) + foreach (var order in catalog.GetAll().Where(order => order.From.Key.Equals(orbit))) + foreach (var good in order.Goods) + wants.Add(good.Key); + return wants; + } +} + +// A standing haul order: goods that move from one station's orbit to another's, keyed haul-order:. A run document: saved +// with the run, cleared, replaced and discarded with it. Fixed until offices issue orders (ruling transit-depots-buy-for-onward-haul); +// From and To are the stations' orbit records until installations give a station a key of its own. +[CultDocument("aetheria.haulorderdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class HaulOrderData +{ + [JsonProperty("from"), Key(0)] public CultRecordRef From; + [JsonProperty("to"), Key(1)] public CultRecordRef To; + [JsonProperty("goods"), Key(2)] public List> Goods = new List>(); + // What stood this order up (scenario:), so a reader can tell a staged order from one an office issues. + [JsonProperty("commitment"), Key(3)] public string Commitment; + + public static CultRecordKey KeyOf(string id) => new CultRecordKey("haul-order:" + id); +} diff --git a/Assets/Scripts/ServerShared/StationWants.cs.meta b/Assets/Scripts/ServerShared/StationWants.cs.meta new file mode 100644 index 000000000..a491ffd4d --- /dev/null +++ b/Assets/Scripts/ServerShared/StationWants.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edaecca4f1754e26af8a65743e4d6da6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/UI/Menu/TradeMenu.cs b/Assets/Scripts/UI/Menu/TradeMenu.cs index 42e56aa07..fa7cec638 100644 --- a/Assets/Scripts/UI/Menu/TradeMenu.cs +++ b/Assets/Scripts/UI/Menu/TradeMenu.cs @@ -297,17 +297,10 @@ public class TradeMenu : MonoBehaviour private void Sell(ItemInstance item) { - if (item is CompoundCommodity compound) + // A commodity stack sells by what the station wants and as far as its bays hold (StationServices.TrySellPart). + if (item is ICommodityStack stack) { - var offered = compound.Quantity; - var sold = StationServices.TrySellPart(_targetCargo, GameManager.DockedEntity, compound, ref GameManager.Credits); - UpdateCreditsLabel(); - Populate(); - if (sold == offered) return; - Dialog.Clear(); - Dialog.Title.text = $"Sold {sold} of {offered}: Station Cargo Full!"; - Dialog.Show(); - Dialog.MoveToCursor(); + Report(StationServices.TrySellPart(_targetCargo, GameManager.DockedEntity, stack, ref GameManager.Credits), GameManager.ItemManager.Title(item)); return; } if (StationServices.TrySell(_targetCargo, GameManager.DockedEntity, item, ref GameManager.Credits)) @@ -322,14 +315,24 @@ public class TradeMenu : MonoBehaviour Dialog.MoveToCursor(); } - // Sells every mined stack of the player's ships' bays in one step; the station pays through TrySell, so nothing refuses. - private void SellOre() + // Refreshes the menu after a commodity sale and says what happened when the station took less than was offered. + private void Report(SaleResult result, string good) { - StationServices.TrySellOre(PlayerBays(), GameManager.DockedEntity, ref GameManager.Credits); UpdateCreditsLabel(); Populate(); + if (result.Refusal == SaleRefusal.None) return; + Dialog.Clear(); + Dialog.Title.text = result.Refusal == SaleRefusal.NotWanted + ? $"{GameManager.DockedEntity.Name} does not buy {good}" + : $"Sold {result.Sold} of {result.Offered}: station hold full"; + Dialog.Show(); + Dialog.MoveToCursor(); } + // Sells every mined stack of the player's ships' bays the station wants in one step, as far as its bays hold them. + private void SellOre() => + Report(StationServices.TrySellOre(PlayerBays(), GameManager.DockedEntity, ref GameManager.Credits), "ore"); + private IEnumerable PlayerBays() => GameManager.CurrentEntity.Parent.Children.Where(e => e is Ship {IsPlayerShip: true}).SelectMany(s => s.CargoBays); @@ -419,7 +422,7 @@ public class TradeMenu : MonoBehaviour }); var repairCost = StationServices.RepairCost(GameManager.ItemManager, GameManager.CurrentEntity); if (repairCost > 0) ContextMenu.AddOption($"Repair ({repairCost:N0})", Repair); - var oreValue = StationServices.OreValue(GameManager.ItemManager, PlayerBays()); + var oreValue = StationServices.OreValue(GameManager.ItemManager, PlayerBays(), GameManager.DockedEntity); if (oreValue > 0) ContextMenu.AddOption($"Sell Ore ({oreValue:N0})", SellOre); ContextMenu.Show(); }); diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 5b1a50aa5..abb012cc4 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0fa325dc5cd816e28d298ebdfda9dc2c5d0af07e8e48198077cafe2223379910 -size 289402 +oid sha256:00e840dbad797c0ce62cb6038dea24963cbda2c273c1f5bcf22481bf2b10f4bf +size 293693 diff --git a/tests/Aetheria.Shared.Tests/CompoundStackTests.cs b/tests/Aetheria.Shared.Tests/CompoundStackTests.cs index 25342da0d..c2f38c613 100644 --- a/tests/Aetheria.Shared.Tests/CompoundStackTests.cs +++ b/tests/Aetheria.Shared.Tests/CompoundStackTests.cs @@ -35,7 +35,9 @@ public sealed class CompoundStackTests : IDisposable foreach (var cell in shape.AllCoordinates) shape[cell] = true; _cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); _cache.Commit(batch => batch.Upsert(typeof(StationKindData), new StationKindData { Name = "Trade Hub" }, StationKindData.KeyOf("trade-hub"))); - _cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Kind = TestStationKinds.TradeHub, Shape = shape, Price = 5000, Durability = 10 }); + _cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Kind = TestStationKinds.TradeHub, Shape = shape, Price = 5000, Durability = 10, + Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = new Shape() } } }); + _cache.Upsert(new GearData { Name = "Smelter", Hardpoint = HardpointType.Facility, Shape = new Shape(), Price = 1, Durability = 4, Behaviors = { new FacilityData() } }); _cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 400, Durability = 8 }); var bay = new Shape(4, 4); foreach (var cell in bay.AllCoordinates) bay[cell] = true; @@ -51,6 +53,16 @@ public sealed class CompoundStackTests : IDisposable foreach (var cell in rodShape.AllCoordinates) rodShape[cell] = true; _rod = new CompoundCommodityData { Name = "Rod", Shape = rodShape, Price = 4, Mass = 1f, SpecificHeat = 1f, MaxStack = 4 }; _cache.Upsert(_rod); + // The fixture station wants what its facility draws: the Smelter's one recipe takes any filler of the role the gem fills, so + // the station wants Gem and not Rod. + var bar = new SimpleCommodityData { Name = "Bar", Shape = new Shape(), Price = 1, MaxStack = 10 }; + _cache.Upsert(bar); + _cache.Upsert(typeof(RecipeData), new RecipeData { Output = _cache.RefOf(_gem), Fills = { "gemmed" } }, RecipeData.KeyOf(_cache.RefOf(_gem).Key)); + _cache.Upsert(typeof(RecipeData), new RecipeData + { + Output = _cache.RefOf(bar), Facility = _cache.RefOf(_cache.GetByName("Smelter")), + RoleInputs = { new ItemRole { Name = "gemmed", Count = 1 } } + }, RecipeData.KeyOf(_cache.RefOf(bar).Key)); _cache.FlushAsync().Wait(); var settings = AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"); @@ -103,10 +115,11 @@ public sealed class CompoundStackTests : IDisposable return ship; } - private OrbitalEntity Station() + private OrbitalEntity Station(bool wants = true) { var station = new OrbitalEntity(_items, _zone, Mint("Hub"), default, new EntitySettings()); Assert.True(station.TryEquip(Mint("Crate"), new int2(1, 1))); + if (wants) Assert.True(station.TryEquip(Mint("Smelter"), new int2(0, 0))); return station; } @@ -454,6 +467,22 @@ public sealed class CompoundStackTests : IDisposable Assert.Equal(Weight(crate), crate.Mass, 3); } + // A station whose gear draws no gem does not buy one: nothing moves and nothing is paid. + [Fact] + public void AStationThatDoesNotWantTheGemRefusesItNotWanted() + { + var from = ShipWith("Crate").CargoBays[0]; + var stack = Gem(_lotA, 3); + Assert.True(from.TryStore(stack)); + var station = Station(wants: false); + var credits = 0; + var result = StationServices.TrySellPart(from, station, stack, ref credits); + Assert.Equal((0, 3, SaleRefusal.NotWanted), (result.Sold, result.Offered, result.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(3, stack.Quantity); + Assert.Empty(station.CargoBays[0].Cargo); + } + [Fact] public void AStackNotInTheHoldSellsNothing() { diff --git a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs index 460c58483..9b2b990b8 100644 --- a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs @@ -6,6 +6,7 @@ using System; using System.Linq; using System.Collections.Generic; using CultMath; +using GameCult.Caching; using UniRx; using Xunit; @@ -59,12 +60,30 @@ public sealed partial class RunStartTests var refinery = StationOfKind(arena, "processing"); var zenith = StationOfKind(arena, "trade-hub"); var credits = 0; - // Every mined stack goes in one sale: the market takes it all, whatever the full hold of the refinery has room for. - var value = StationServices.OreValue(_items, player.CargoBays); + // The refinery buys the mined ore as far as its bays hold it (ruling no-market-absorption): the units it took are paid for, and + // what did not fit stays in the hold. + var value = StationServices.OreValue(_items, player.CargoBays, refinery); Assert.True(value > 0); - Assert.Equal(gains.Sum(gain => gain.Stored), StationServices.TrySellOre(player.CargoBays, refinery, ref credits)); - Assert.Equal(value, credits); - Assert.DoesNotContain(player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()), c => ores.Contains(_items.GetData(c).Name)); + var mined = gains.Sum(gain => gain.Stored); + var sale = StationServices.TrySellOre(player.CargoBays, refinery, ref credits); + Assert.Equal(mined, sale.Offered); + Assert.True(sale.Sold > 0, "the refinery has room for some of the ore"); + var left = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Where(c => ores.Contains(_items.GetData(c).Name)).Sum(c => c.Quantity); + Assert.Equal(mined - sale.Sold, left); + if (left == 0) Assert.Equal(value, credits); + else Assert.True(credits > 0 && credits < value); + + // Zenith's silo wants the ores of the haul order to the refinery: it buys what the hold still carries, and a fresh stack too. + var zenithWants = StationWants.Of(zenith); + Assert.NotEmpty(zenithWants); + Assert.All(zenithWants, good => Assert.True(FieldKinds.IsOre(_cache, _cache.Get(new CultRecordRef(good))))); + var silo = zenith.CargoBays.Single(bay => bay.Data is SiloData); + var oreGood = zenithWants.OrderBy(good => good.Value, StringComparer.Ordinal).First(); + var fresh = new SimpleCommodity { Data = new CultRecordRef(oreGood), Quantity = 5 }; + Assert.True(player.CargoBays[0].TryStore(fresh)); + var atZenith = StationServices.TrySellPart(player.CargoBays[0], zenith, fresh, ref credits); + Assert.Equal((5, SaleRefusal.None), (atZenith.Sold, atZenith.Refusal)); + Assert.Equal(5, silo.Count(oreGood)); var cell = Enumerable.Range(0, player.MaxArmor.GetLength(0)).SelectMany(x => Enumerable.Range(0, player.MaxArmor.GetLength(1)).Select(y => (x, y))) .First(c => player.MaxArmor[c.x, c.y] > 0); @@ -96,14 +115,14 @@ public sealed partial class RunStartTests // with all its armour lost and against the authored Price of the cheapest piece Zenith stocks (ruling demo-loop-reads-authored-price: // the rolled BuyPrice moves with any catalog change that shifts the stock draw, 47053 against 36806 for the same Ring Station Reactor // across design-bills, which is not what this test is about). Margin rule: the anchors are the readings the shipped catalog gives at - // design-bills (V 282.149, repair 55404, cheapest authored price 15500), and the band is 1/sqrt(10) to sqrt(10) of each, the + // design-bills (V 282.149, repair 55404, cheapest authored price 15500; the price re-read at station-sale-by-wants as 2500, since generated stock stops at half the bay and the smaller, cheaper pieces then fit where the full bay refused them), and the band is 1/sqrt(10) to sqrt(10) of each, the // geometric midpoint between the shipped reading and the least mutant this test claims to catch (a divisor of ten on either side, a // ratio of 10 or 0.1): the shipped reading and that mutant each sit 3.16x from a bound. // The one station of a kind in the arena: the demo's two stations are told apart by what they are for, never by hull. private static OrbitalEntity StationOfKind(Zone arena, string kind) => arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf(kind))); - private const double BaseRepairRatio = 0.0050925, BaseBuyRatio = 0.018203; + private const double BaseRepairRatio = 0.0050925, BaseBuyRatio = 0.11286; private static readonly double Margin = Math.Sqrt(10); [Fact] diff --git a/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs index cedbf6926..8ade9b7f4 100644 --- a/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs @@ -250,15 +250,19 @@ public sealed class EconomyLoopTests public void AFullHoldSortieIsPricedFromTheShipItEndedWith() { int ore = -1, repair = -1; - var sample = EconomyLoop.Sortie(Root, 1, 0, 300, (ship, items) => + var sample = EconomyLoop.Sortie(Root, 1, 0, 300, (ship, items, processing) => { - ore = StationServices.OreValue(items, ship.CargoBays); + ore = StationServices.OreValue(items, ship.CargoBays, processing); repair = StationServices.RepairCost(items, ship); }); Assert.Equal(LoopOutcome.Full, sample.Outcome); Assert.True(sample.HoldFullAt > 0 && sample.HoldFullAt <= sample.SimSeconds); Assert.True(sample.SellValue > 0); - Assert.Equal(ore, sample.SellValue); + // The station pays for the units its bays took: what it would pay for all of them, less what it refused for want of room. + Assert.Equal(ore, sample.OfferedValue); + Assert.True(sample.SellValue <= sample.OfferedValue); + Assert.Equal(sample.Units, sample.UnitsSold + sample.UnitsRefused); + if (sample.UnitsRefused == 0) Assert.Equal(sample.OfferedValue, sample.SellValue); Assert.True(sample.Repair > 0); Assert.Equal(repair, sample.Repair); // Laser fit: no ammunition is spent. @@ -269,7 +273,7 @@ public sealed class EconomyLoopTests public void ASortieThatSpendsItsStarterAmmunitionEndsAmmoOutAndPaysForIt() { var ammoLeft = -1; - var sample = EconomyLoop.Sortie(Root, 2, 0, 150, (ship, items) => + var sample = EconomyLoop.Sortie(Root, 2, 0, 150, (ship, items, _) => ammoLeft = ship.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Where(c => items.GetData(c).Name == "Ammo").Sum(c => c.Quantity)); Assert.Equal(LoopOutcome.AmmoOut, sample.Outcome); Assert.Equal(0, ammoLeft); diff --git a/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs b/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs index 044f7201a..e58fd6de9 100644 --- a/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs +++ b/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs @@ -28,7 +28,7 @@ public sealed class StationFacilityFitTests .Where(kind => cache.Get(kind).Facilities.Count > 0) .SelectMany(kind => Enumerable.Range(1, 6).Select(seed => (faction, kind, (uint) seed)))); - private static string[] FacilityKeys(Entity station) => station.Equipment.Where(item => item.Data.HardpointType == HardpointType.Facility) + private static string[] FacilityKeys(Entity station) => station.Equipment.Concat(station.CargoBays).Where(item => item.Data.HardpointType == HardpointType.Facility) .Select(item => item.Data.Name).OrderBy(name => name, StringComparer.Ordinal).ToArray(); [Fact] @@ -42,7 +42,7 @@ public sealed class StationFacilityFitTests var (items, station) = Generate(cache, maker, kind, seed); var wanted = cache.Get(kind).Facilities.Select(facility => cache.Get(facility).Name).OrderBy(name => name, StringComparer.Ordinal).ToArray(); Assert.Equal(wanted, FacilityKeys(station)); - Assert.All(station.Equipment.Where(item => item.Data.HardpointType == HardpointType.Facility), + Assert.All(station.Equipment.Concat(station.CargoBays).Where(item => item.Data.HardpointType == HardpointType.Facility), item => Assert.Equal(HardpointType.Facility, item.Hardpoint.Type)); } } diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index e7ca46f7d..fd604935a 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -24,7 +24,11 @@ public sealed class StationServicesTests : IDisposable 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, Armor = 10, Hardpoints = { hardpoint } }); - _cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10 }); + _cache.Upsert(new HullData + { + Name = "Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10, + Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = new Shape() } } + }); _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 = "Sweep", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Durability = 20 }); @@ -42,6 +46,15 @@ public sealed class StationServicesTests : IDisposable Yields = { new FieldYield { Commodity = _cache.RefOf(ore), Abundance = 1f } } }); _cache.Upsert(new SimpleCommodityData { Name = "Shells", Shape = new Shape(), Price = 3, MaxStack = 100 }); + // The fixture station wants what its Smelter's one recipe draws: Ore, and not Shells. + var bar = new SimpleCommodityData { Name = "Bar", Shape = new Shape(), Price = 9, MaxStack = 100 }; + _cache.Upsert(bar); + _cache.Upsert(new GearData { Name = "Smelter", Hardpoint = HardpointType.Facility, Shape = new Shape(), Price = 1, Durability = 4, Behaviors = { new FacilityData() } }); + _cache.Upsert(typeof(RecipeData), new RecipeData + { + Output = _cache.RefOf(bar), Facility = _cache.RefOf(_cache.GetByName("Smelter")), + Inputs = { new CommodityCount { Commodity = _cache.RefOf(ore), Count = 1 } } + }, RecipeData.KeyOf(_cache.RefOf(bar).Key)); _cache.FlushAsync().Wait(); var settings = AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"); @@ -79,10 +92,11 @@ public sealed class StationServicesTests : IDisposable } // A station whose one cargo bay can take the goods, or one with no cargo bay at all. - private OrbitalEntity Station(bool withBay = true) + private OrbitalEntity Station(bool withBay = true, bool wants = 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))); + if (withBay && wants) Assert.True(station.TryEquip(Mint("Smelter"), new int2(0, 0))); return station; } @@ -134,9 +148,7 @@ public sealed class StationServicesTests : IDisposable 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; @@ -145,12 +157,6 @@ public sealed class StationServicesTests : IDisposable 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)); @@ -160,6 +166,45 @@ public sealed class StationServicesTests : IDisposable Assert.Equal(1000, credits); Assert.Equal(packed, from.Cargo.Count); Assert.Contains(other, from.Cargo.Keys); + + // A commodity stack never sells through TrySell: it has no unit count to say how many sold. + Assert.Throws(() => StationServices.TrySell(from, station, Ore(10), ref credits)); + } + + // A commodity sells by what the station's installed gear draws: the Smelter's recipe takes Ore, so Ore sells whole into room and + // Shells, which no facility draws, are NotWanted with nothing moved (ruling installed-gear-decides-what-a-station-buys). + [Fact] + public void AStationBuysOnlyWhatItsGearWants() + { + var from = Ship().CargoBays.Single(); + var ore = Ore(10); + var shells = Shells(5); + Assert.True(from.TryStore(ore)); + Assert.True(from.TryStore(shells)); + var station = Station(); + Assert.Equal(new[] { _cache.RefOf(_cache.GetByName("Ore")).Key }, StationWants.Of(station)); + + var credits = 1000; + var sold = StationServices.TrySellPart(from, station, ore, ref credits); + Assert.Equal((10, 10, SaleRefusal.None), (sold.Sold, sold.Offered, sold.Refusal)); + Assert.Equal(1035, credits); + Assert.DoesNotContain(ore, from.Cargo.Keys); + Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); + + var refused = StationServices.TrySellPart(from, station, shells, ref credits); + Assert.Equal((0, 5, SaleRefusal.NotWanted), (refused.Sold, refused.Offered, refused.Refusal)); + Assert.Equal(1035, credits); + Assert.Contains(shells, from.Cargo.Keys); + Assert.Equal(5, shells.Quantity); + + // A station with no facility wants nothing, Ore included. + var bare = Station(wants: false); + Assert.Empty(StationWants.Of(bare)); + var held = Ore(1); + Assert.True(from.TryStore(held)); + var none = StationServices.TrySellPart(from, bare, held, ref credits); + Assert.Equal((0, 1, SaleRefusal.NotWanted), (none.Sold, none.Offered, none.Refusal)); + Assert.Equal(1035, credits); } // A station's first bay being full is no reason to refuse: the goods go to whichever bay takes them. @@ -180,11 +225,41 @@ public sealed class StationServicesTests : IDisposable var credits = 0; Assert.True(StationServices.TrySell(from, station, gun, ref credits)); - Assert.True(StationServices.TrySell(from, station, ore, ref credits)); + Assert.Equal(10, StationServices.TrySellPart(from, station, ore, ref credits).Sold); Assert.Contains(gun, open.Cargo.Keys); Assert.Contains(ore, open.Cargo.Keys); } + // Nothing is absorbed (ruling no-market-absorption): a hold with room for some units takes those and pays for those + // alone, the rest stays in the seller's hold, and a hold with no room pays nothing. + [Fact] + public void AFullStationHoldTakesOnlyWhatFits() + { + var from = Ship().CargoBays.Single(); + var station = Station(); + var bay = station.CargoBays[0]; + // The station's one ore stack holds 60 of its 100 and every other cell holds a gun: 40 units fit. + var shelf = Ore(60); + Assert.True(bay.TryStore(shelf)); + while (bay.TryStore(Mint("Gun"))) { } + var big = Ore(100); + Assert.True(from.TryStore(big)); + var credits = 0; + var result = StationServices.TrySellPart(from, station, big, ref credits); + Assert.Equal((40, 100, SaleRefusal.NoRoom), (result.Sold, result.Offered, result.Refusal)); + Assert.Equal(StationServices.SellPrice(_items, Ore(40)), credits); + Assert.Contains(big, from.Cargo.Keys); + Assert.Equal(60, big.Quantity); + Assert.Equal(100, shelf.Quantity); + + // Now the stack is full and no cell is free: nothing sells, nothing is paid, the stack stays. + credits = 0; + var refused = StationServices.TrySellPart(from, station, big, ref credits); + Assert.Equal((0, 60, SaleRefusal.NoRoom), (refused.Sold, refused.Offered, refused.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(60, big.Quantity); + } + // A commodity the seller does not hold sells for nothing: not one never stored, and not a stale copy of a stack the sale // already took. The held stack is untouched, and no credit is paid. [Fact] @@ -196,14 +271,14 @@ public sealed class StationServicesTests : IDisposable var station = Station(); var credits = 500; - Assert.False(StationServices.TrySell(from, station, Ore(10), ref credits)); + Assert.Equal(0, StationServices.TrySellPart(from, station, Ore(10), ref credits).Sold); Assert.Equal(500, credits); Assert.Empty(station.CargoBays.Single().Cargo.Keys.OfType()); Assert.Equal(10, Assert.Single(from.Cargo.Keys.OfType()).Quantity); - Assert.True(StationServices.TrySell(from, station, held, ref credits)); + Assert.Equal(10, StationServices.TrySellPart(from, station, held, ref credits).Sold); var paid = credits; - Assert.False(StationServices.TrySell(from, station, held, ref credits)); + Assert.Equal(0, StationServices.TrySellPart(from, station, held, ref credits).Sold); Assert.Equal(paid, credits); Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); } @@ -511,12 +586,12 @@ public sealed class StationServicesTests : IDisposable Assert.True(bay.TryStore(shells)); Assert.True(bay.TryStore(gun)); var station = Station(); - var value = StationServices.OreValue(_items, ship.CargoBays); + var value = StationServices.OreValue(_items, ship.CargoBays, station); Assert.Equal(StationServices.SellPrice(_items, bought), value); Assert.True(value > 0); var credits = 100; - Assert.Equal(10, StationServices.TrySellOre(ship.CargoBays, station, ref credits)); + Assert.Equal(10, StationServices.TrySellOre(ship.CargoBays, station, ref credits).Sold); Assert.Equal(100 + value, credits); Assert.DoesNotContain(bought, bay.Cargo.Keys); Assert.Contains(shells, bay.Cargo.Keys); @@ -532,15 +607,26 @@ public sealed class StationServicesTests : IDisposable Assert.True(one.CargoBays.Single().TryStore(Ore(30))); Assert.True(two.CargoBays.Single().TryStore(Ore(40))); var station = Station(); - // Fill the station's bay so nothing more fits: the market absorbs the sale at full price all the same. - for (var i = 0; i < 20; i++) station.CargoBays.Single().TryStore(Ore(100)); - var value = StationServices.OreValue(_items, bays); + var value = StationServices.OreValue(_items, bays, station); Assert.Equal(StationServices.SellPrice(_items, Ore(70)), value); + // Across bays, a station with room takes all of it and pays for all of it. var credits = 0; - Assert.Equal(70, StationServices.TrySellOre(bays, station, ref credits)); + var roomy = StationServices.TrySellOre(bays, station, ref credits); + Assert.Equal((70, 70), (roomy.Sold, roomy.Offered)); Assert.Equal(value, credits); Assert.All(bays, bay => Assert.Empty(bay.Cargo.Keys.OfType())); + + // The full station takes nothing: credits 0, the 70 units stay. + Assert.True(one.CargoBays.Single().TryStore(Ore(30))); + Assert.True(two.CargoBays.Single().TryStore(Ore(40))); + var full = Station(); + while (full.CargoBays.Single().TryStore(Mint("Gun"))) { } + credits = 0; + var refused = StationServices.TrySellOre(bays, full, ref credits); + Assert.Equal((0, 70, SaleRefusal.NoRoom), (refused.Sold, refused.Offered, refused.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(70, bays.SelectMany(bay => bay.Cargo.Keys.OfType()).Sum(stack => stack.Quantity)); } [Fact] @@ -552,8 +638,8 @@ public sealed class StationServicesTests : IDisposable Assert.True(bay.TryStore(Mint("Gun"))); var held = bay.Cargo.Count; var credits = 100; - Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); - Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); + Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays, Station())); + Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits).Sold); Assert.Equal(100, credits); Assert.Equal(held, bay.Cargo.Count); } diff --git a/tests/Aetheria.Shared.Tests/StationWantsTests.cs b/tests/Aetheria.Shared.Tests/StationWantsTests.cs new file mode 100644 index 000000000..b07210b8d --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationWantsTests.cs @@ -0,0 +1,189 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; +using float2 = CultMath.float2; + +// What a station buys on the shipped catalog (aetheria-living-world, cut station-sale-by-wants; rulings +// installed-gear-decides-what-a-station-buys, transit-depots-buy-for-onward-haul, demo-zenith-ore-depot, no-market-absorption): +// a recipe facility's draws, a silo's haul order, the silo as a bay, the order as a run record, and the room generated stock leaves. +public sealed partial class RunStartTests +{ + // A hold that holds `units` of every design but the excluded ones. + private sealed class FullHold : IProductionHold + { + private readonly HashSet _without; + public FullHold(IEnumerable without = null) => _without = new HashSet(without ?? Array.Empty()); + public int Held(CultRecordKey design) => _without.Contains(design) ? 0 : 1000; + public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) => true; + public bool TryPut(CultRecordKey design, int units) => true; + } + + private IEnumerable ShippedFacilityDesigns() => + _cache.GetAll().SelectMany(kind => kind.Facilities).Select(facility => facility.Key).Distinct() + .Where(key => StationKinds.IsRecipeFacility(_cache.Get(new CultRecordRef(key)))); + + // Production.Draws names every design Take can take: with every good in the hold, and with each filler of each role the only one. + [Fact] + public void DrawsNamesEveryDesignTakeTakes() + { + var checkedRecipes = 0; + foreach (var facility in ShippedFacilityDesigns()) + foreach (var recipe in Production.RunList(_cache, facility)) + { + var draws = Production.Draws(_cache, recipe); + var all = Production.Take(_cache, recipe, new FullHold()); + Assert.NotNull(all); + Assert.All(all, entry => Assert.Contains(entry.design, draws)); + foreach (var role in Recipes.RoleInputsOf(_cache, recipe)) + { + var fillers = Recipes.Fillers(_cache, role.Name); + foreach (var only in fillers) + { + var taken = Production.Take(_cache, recipe, new FullHold(fillers.Where(filler => !filler.Equals(only)))); + Assert.NotNull(taken); + Assert.All(taken, entry => Assert.Contains(entry.design, draws)); + Assert.Contains(taken, entry => entry.design.Equals(only)); + } + } + checkedRecipes++; + } + Assert.True(checkedRecipes > 10, $"{checkedRecipes} recipes checked"); + } + + // The wants of the Pirates' refinery are the draws of its run list and nothing else: Gun Forging makes a compound, so it is on the + // facility's RunOn list but not its run list, and what only it draws is not wanted. + [Fact] + public void AFacilityThatRunsNothingWantsNothing() + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var refinery = StationOfKind(arena, "processing"); + var design = refinery.Equipment.Select(equipped => _items.GetData(equipped.EquippableItem)).Single(data => StationKinds.IsRecipeFacility(data)); + var key = _cache.RefOf(design).Key; + var run = Production.RunList(_cache, key); + var drawn = new HashSet(run.SelectMany(recipe => Production.Draws(_cache, recipe))); + Assert.Equal(drawn.OrderBy(good => good.Value, StringComparer.Ordinal), StationWants.Of(refinery).OrderBy(good => good.Value, StringComparer.Ordinal)); + + var skipped = Recipes.RunOn(_cache, key).Except(run).ToArray(); + Assert.NotEmpty(skipped); + var onlySkipped = skipped.SelectMany(recipe => Production.Draws(_cache, recipe)).Where(good => !drawn.Contains(good)).ToArray(); + Assert.NotEmpty(onlySkipped); + Assert.Empty(StationWants.Of(refinery).Intersect(onlySkipped)); + } + + private OrbitalEntity DemoStation(string kind, uint seed = 1) + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + return StationOfKind(arena, kind); + } + + // Zenith's silo is a bay on its Facility row, in CargoBays and not in Equipment; it survives a pack and restore, takes ore and + // refuses gear and consumables, and generated gear stock never lands in it. + [Fact] + public void ASiloIsABayOnItsFacilityRowAndHoldsBulkOnly() + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var zenith = StationOfKind(arena, "trade-hub"); + var silo = Assert.Single(zenith.CargoBays, bay => bay.Data is SiloData); + Assert.NotNull(silo.Hardpoint); + Assert.Equal(HardpointType.Facility, silo.Hardpoint.Type); + Assert.DoesNotContain(zenith.Equipment, equipped => equipped.Data is SiloData); + Assert.Empty(silo.Cargo); + Assert.Contains(zenith.CargoBays, bay => !(bay.Data is SiloData) && bay.Cargo.Count > 0); + + var ore = StationWants.Of(zenith).OrderBy(good => good.Value, StringComparer.Ordinal).First(); + Assert.True(silo.TryStore(new SimpleCommodity { Data = new CultRecordRef(ore), Quantity = 3 })); + var gear = _cache.GetAll().First(data => data.HardpointType == HardpointType.Sensors); + var instance = _items.CreateInstance(_cache.GetAll().First(product => product.Design.Key.Equals(_cache.RefOf(gear).Key))); + Assert.False(silo.TryStore(instance)); + Assert.False(silo.TryFindSpace(instance)); + + var restored = EntitySerializer.Unpack(_items, arena, EntitySerializer.Pack(zenith)); + var restoredSilo = Assert.Single(restored.CargoBays, bay => bay.Data is SiloData); + Assert.Equal(3, restoredSilo.Count(ore)); + Assert.Equal(zenith.CargoBays.Count, restored.CargoBays.Count); + } + + // Zenith buys ore for its haul order: with the order removed, or the silo removed, it buys none. + [Fact] + public void ZenithBuysOnlyTheHaulOrdersGoods() + { + var zenith = DemoStation("trade-hub"); + var order = Assert.Single(_cache.GetAll()); + Assert.Equal(order.Goods.Select(good => good.Key).OrderBy(good => good.Value, StringComparer.Ordinal), StationWants.Of(zenith).OrderBy(good => good.Value, StringComparer.Ordinal)); + Assert.NotEmpty(order.Goods); + Assert.All(order.Goods, good => Assert.True(FieldKinds.IsOre(_cache, _cache.Get(good)))); + + // The same station without its silo (a copy, since a placed station is active) wants nothing: its goods are its silo's. + var copy = (OrbitalEntity) EntitySerializer.Unpack(_items, zenith.Zone, EntitySerializer.Pack(zenith)); + Assert.Equal(StationWants.Of(zenith).Count, StationWants.Of(copy).Count); + Assert.NotNull(copy.TryUnequip(copy.CargoBays.Single(bay => bay.Data is SiloData))); + Assert.Empty(StationWants.Of(copy)); + + var key = _cache.AllStoredDocuments.Single(stored => stored.Descriptor.DocumentType == typeof(HaulOrderData)).Key; + _cache.Commit(batch => batch.Remove(key)); + Assert.Empty(StationWants.Of(zenith)); + } + + // The staged order is a run record: Clear and a discarded Simulation remove it, and a refused stage writes none. + [Fact] + public void HaulOrderGoesWithTheRun() + { + Assert.True(RunSave.IsRunRecord(typeof(HaulOrderData))); + var (started, simulation) = RunSave.Beside(_cache, () => + { + var (_, _, _, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + return new object(); + }); + Assert.NotNull(started); + Assert.Single(_cache.GetAll()); + simulation.Discard(_cache); + Assert.Empty(_cache.GetAll()); + + Launch(new DemoTerminus(), Inputs(() => 2)); + Assert.Single(_cache.GetAll()); + RunSave.Clear(_cache); + Assert.Empty(_cache.GetAll()); + + // A stage that queues an order and then fails writes nothing. + var (_, _, staged, refused) = Launch(new Scripted(false, stage => + { + var station = stage.Arena.Entities.OfType().First(); + stage.HaulOrder("refused", station, station, new[] { new CultRecordRef(new CultRecordKey("commodity:iron")) }, "scenario:test"); + stage.Station("no-such-kind"); + stage.Player(stage.Generated(""), float2.zero); + }), Inputs()); + Assert.Null(staged); + Assert.Contains(refused, failure => failure.Contains("no-such-kind")); + Assert.DoesNotContain(refused, failure => failure.Contains("orbit")); + Assert.Empty(_cache.GetAll()); + } + + // Generated gear stock stops at half the stock bay: every demo station keeps at least (1 - StationStockShare) of its cells free. + [Fact] + public void GeneratedStockLeavesRoom() + { + foreach (var seed in new uint[] { 1, 2, 3, 4, 5, 69, 97 }) + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, $"seed {seed}: " + string.Join("; ", failures)); + foreach (var station in arena.Entities.OfType().Where(entity => entity.HullData.HullType == HullType.Station)) + { + var bay = station.CargoBays.First(candidate => !(candidate.Data is SiloData)); + var cells = bay.Data.InteriorShape.Coordinates.Length; + var free = bay.Data.InteriorShape.Coordinates.Count(cell => bay.Occupancy[cell.x, cell.y] == null); + var floor = cells - (int) (cells * LoadoutGenerator.StationStockShare); + Assert.True(free >= floor, $"seed {seed} {station.Name}: {free} of {cells} cells free, at least {floor} wanted"); + } + } + } +} diff --git a/tools/AetherDb/Economy/Facilities.cs b/tools/AetherDb/Economy/Facilities.cs index afc80287a..af1503738 100644 --- a/tools/AetherDb/Economy/Facilities.cs +++ b/tools/AetherDb/Economy/Facilities.cs @@ -29,6 +29,11 @@ public sealed class Facilities : EconomyBatch ("munitions-works", "munitions-line", "Munitions Line", "A sealed line that makes energetics and loads rounds, primers, fuzes, warheads and motors."), }; + // The one storage facility: Zenith's ore silo (ruling demo-zenith-ore-depot). Storage, not a recipe facility, so it has no recipe and + // its kind is named here; a silo is bulk storage on a Facility row and holds only commodity stacks (SiloData). + private static readonly (string Kind, string Id, string Name, string Description) Silo = + ("trade-hub", "ore-silo", "Ore Silo", "A sealed bulk store that holds ore waiting for the haul to the refinery."); + // The kind's first facility design, or unset: the one lookup the recipe-writing batches use. public static CultRecordRef Of(CultCache catalog, string kindId) { @@ -67,9 +72,7 @@ public sealed class Facilities : EconomyBatch Durability = 100, Mass = 250, Price = 1000, Behaviors = { new FacilityData() }, MinimumTemperature = ThermalMin, MaximumTemperature = ThermalMax, OptimalTemperature = ThermalOptimal, PlateauWidth = ThermalPlateau }, designKey); - var factions = catalog.GetAll().Select(faction => (Key: catalog.RefOf(faction).Key, Faction: faction)).OrderBy(pair => pair.Key.Value, StringComparer.Ordinal).ToArray(); - var maker = factions.FirstOrDefault(pair => StationKinds.KindsOf(catalog, pair.Faction).Any(kind => kind.Key.Value == kindKey)); - if (maker.Faction == null) maker = factions.First(); + var maker = MakerOf(catalog, kindKey); // The brand lives in the product (ruling designs-are-tech-nodes): the maker's name before the design's. Put(new FactionProductData { @@ -84,6 +87,7 @@ public sealed class Facilities : EconomyBatch author.Put(kind, new CultRecordKey(kindKey)); } } + AuthorSilo(author, catalog, (wanted, key) => Put(wanted, key)); foreach (var recipe in catalog.GetAll().ToArray()) { var facility = FirstOf(catalog.Get(recipe.StationKind)); @@ -92,4 +96,47 @@ public sealed class Facilities : EconomyBatch author.Put(recipe, catalog.RefOf(recipe).Key); } } + + // The first faction by key that places the kind, else the first by key: the brand of a facility's product. + private static (CultRecordKey Key, Faction Faction) MakerOf(CultCache catalog, string kindKey) + { + var factions = catalog.GetAll().Select(faction => (Key: catalog.RefOf(faction).Key, Faction: faction)).OrderBy(pair => pair.Key.Value, StringComparer.Ordinal).ToArray(); + var maker = factions.FirstOrDefault(pair => StationKinds.KindsOf(catalog, pair.Faction).Any(kind => kind.Key.Value == kindKey)); + return maker.Faction == null ? factions.First() : maker; + } + + // The silo design, its NotOffered product, and its kind's Facilities holding it: each only where it differs. Compared by fields, as + // the recipe facilities are. + private static void AuthorSilo(EconomyAuthor author, CultCache catalog, Action put) + { + var (kindId, id, name, description) = Silo; + var designKey = new CultRecordKey("facility:" + id); + var shape = new Shape(2, 2); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var interior = new Shape(8, 8); + foreach (var cell in interior.AllCoordinates) interior[cell] = true; + if (!(catalog.Get(designKey) is SiloData held && held.Name == name && held.Description == description + && held.Durability == 100 && held.Mass == 250 && held.Price == 1000 && held.Shape.Width == 2 && held.Shape.Height == 2 && held.Shape.Coordinates.Length == 4 + && held.InteriorShape.Width == 8 && held.InteriorShape.Height == 8 && held.InteriorShape.Coordinates.Length == 64 + && held.MinimumTemperature == ThermalMin && held.MaximumTemperature == ThermalMax && held.OptimalTemperature == ThermalOptimal && held.PlateauWidth == ThermalPlateau)) + author.Put(new SiloData + { + Name = name, Description = description, Shape = shape, InteriorShape = interior, + Durability = 100, Mass = 250, Price = 1000, + MinimumTemperature = ThermalMin, MaximumTemperature = ThermalMax, OptimalTemperature = ThermalOptimal, PlateauWidth = ThermalPlateau + }, designKey); + var kindKey = StationKindData.KeyOf(kindId); + var maker = MakerOf(catalog, kindKey.Value); + put(new FactionProductData + { + Name = $"{maker.Faction.Name} {name}", Description = description, Design = new CultRecordRef(designKey), + Manufacturer = new CultRecordRef(maker.Key), NotOffered = true + }, new CultRecordKey("product:facility:" + id)); + var kind = catalog.Get(kindKey) ?? throw new InvalidOperationException($"The silo's station kind '{kindId}' is not in the catalog."); + if (kind.Facilities.Count != 1 || !kind.Facilities[0].Key.Equals(designKey)) + { + kind.Facilities = new List> { new CultRecordRef(designKey) }; + author.Put(kind, kindKey); + } + } } diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 9555919a2..cfbb2afc3 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -165,10 +165,10 @@ public static class EconomyCommand private static void PrintLoop(LoopReport loop, TextWriter output) { var inv = System.Globalization.CultureInfo.InvariantCulture; - output.WriteLine("\nPlayer loop (seed belt | kind | weapons | outcome | rocks | sim s | hold full at | units | sell | ammo | repair | net per minute)"); + output.WriteLine("\nPlayer loop (seed belt | kind | weapons | outcome | rocks | sim s | hold full at | units | sold | refused | offered value | sell | ammo | repair | net per minute)"); foreach (var s in loop.Samples) - output.WriteLine(string.Format(inv, " {0} {11}/{12} | {1} | {2} | {13} | {3} | {4:0.#} | {5} | {6} | {7} | {8} | {9} | {10:0.#}", s.Seed, s.BeltKind, s.Weapons, s.Rocks, s.SimSeconds, - s.HoldFullAt.HasValue ? s.HoldFullAt.Value.ToString("0.#", inv) + " s" : "never", s.Units, s.SellValue, s.AmmoSpent, s.Repair, s.RatePerMinute, s.Belt + 1, s.Belts, s.Outcome)); + output.WriteLine(string.Format(inv, " {0} {11}/{12} | {1} | {2} | {13} | {3} | {4:0.#} | {5} | {6} | {14} | {15} | {16} | {7} | {8} | {9} | {10:0.#}", s.Seed, s.BeltKind, s.Weapons, s.Rocks, s.SimSeconds, + s.HoldFullAt.HasValue ? s.HoldFullAt.Value.ToString("0.#", inv) + " s" : "never", s.Units, s.SellValue, s.AmmoSpent, s.Repair, s.RatePerMinute, s.Belt + 1, s.Belts, s.Outcome, s.UnitsSold, s.UnitsRefused, s.OfferedValue)); output.WriteLine(string.Format(inv, " median {0:0.#} per minute, best {1:0.#} per minute over the {3} sorties that mined to a full hold or the cap; purse {2}", loop.Median, loop.Best, loop.Purse, loop.Samples.Count(s => s.Measured))); output.WriteLine(string.Format(inv, " median net per sortie {0:0.#} (the afford band counts sorties of this net, resting on {1} measured sorties)", loop.MedianNet, loop.MeasuredSorties)); string Minutes(double? m) => m.HasValue ? m.Value.ToString("0.#", inv) : "-"; diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs index 0924f9711..296dcffe0 100644 --- a/tools/AetherDb/EconomyLoop.cs +++ b/tools/AetherDb/EconomyLoop.cs @@ -38,7 +38,12 @@ public sealed class LoopSample public int Units; // The sim second the first unit floated, i.e. the hold was full; null if it never filled. public double? HoldFullAt; + // What the arena's processing station paid for the hold at sortie end (TrySellOre), and what it would have paid for every ore + // stack it wants had its bays had room (OreValue); the units it took and the units it refused for want of room. public int SellValue; + public int OfferedValue; + public int UnitsSold; + public int UnitsRefused; public int AmmoSpent; public int Repair; @@ -109,9 +114,9 @@ public static class EconomyLoop // One sortie in the demo run of this seed on one belt: the staged ship is held forty units off each rock of the belt in index // order, fires every weapon at it, and stops when the first unit floats (the hold is full), when a starting stock runs out, or // at the cap. Everything it touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a - // shared one advances its Random and gave the same seed different results). atEnd, if given, sees the ship and items as the + // shared one advances its Random and gave the same seed different results). atEnd, if given, sees the ship, items and the processing station as the // sample is taken, so a test can read the same state the sample was priced from. - public static LoopSample Sortie(string root, uint seed, int beltIndex, float capSeconds, Action atEnd = null) + public static LoopSample Sortie(string root, uint seed, int beltIndex, float capSeconds, Action atEnd = null) { if (!float.IsFinite(capSeconds) || capSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(capSeconds), "the cap must be a positive, finite number of sim seconds"); var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loop-" + Guid.NewGuid().ToString("N"))).FullName; @@ -136,6 +141,8 @@ public static class EconomyLoop var failures = new List(); var player = RunStart.Stage(items, arena, scenario, startingHull, failures).Player; if (failures.Count > 0) throw new InvalidOperationException($"seed {seed}: staging failed: {string.Join("; ", failures)}"); + // The station that buys the sortie's ore, found by what it is for. + var processing = arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf("processing"))); var belts = arena.Planets.Where(body => body.Value is AsteroidBeltData).ToList(); if (beltIndex < 0 || beltIndex >= Math.Max(belts.Count, 1)) throw new ArgumentOutOfRangeException(nameof(beltIndex), $"seed {seed} has {belts.Count} belts"); @@ -212,7 +219,7 @@ public static class EconomyLoop sample.SimSeconds = ticks * (double) Step; sample.Units = units; sample.HoldFullAt = fullTick == null ? null : fullTick * (double) Step; - sample.SellValue = StationServices.OreValue(items, player.CargoBays); + sample.OfferedValue = StationServices.OreValue(items, player.CargoBays, processing); sample.AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue); sample.Repair = StationServices.RepairCost(items, player); if (fullTick != null) sample.Outcome = LoopOutcome.Full; @@ -220,7 +227,13 @@ public static class EconomyLoop else if (targeted == 0) { sample.Outcome = LoopOutcome.RigFault; sample.Note = "no rock of the belt could be targeted"; } else if (ticks >= capTicks) sample.Outcome = LoopOutcome.Capped; else { sample.Outcome = LoopOutcome.RigFault; sample.Note = "ran out of rocks before the cap"; } - atEnd?.Invoke(player, items); + atEnd?.Invoke(player, items, processing); + // The hold sells to the processing station: it pays for the units its bays take, and the rest stays aboard. + var credits = 0; + var sale = StationServices.TrySellOre(player.CargoBays, processing, ref credits); + sample.SellValue = credits; + sample.UnitsSold = sale.Sold; + sample.UnitsRefused = sale.Offered - sale.Sold; return sample; } finally