From e8c7d8e1d131c214fe8dcc83ee0f5626b9e4236a Mon Sep 17 00:00:00 2001 From: soul Date: Tue, 1 Dec 2026 15:33:29 +0100 Subject: [PATCH] StationWants: a drawn good stops at its share of the stock bays (Holding), split by the rate installed recipes consume it Ruling stations-buy-ingredients-to-target-share. LandingOf's drawn branch no longer yields int.MaxValue room: it yields Holding less the units held over all bays. Holding is derived per call from the installed recipe facility units (a slot per Input, Upkeep and role, at count over the run list's summed cycles), floored at one cycle, one stack for a crew-only good. balance --region prints inputs held at end with each holding. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/ServerShared/StationWants.cs | 90 ++++-- .../StationWantsTests.cs | 280 ++++++++++++++++++ tools/AetherDb/EconomyRegion.cs | 10 + 3 files changed, 363 insertions(+), 17 deletions(-) diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs index d1ea24ec6..cb228d1fa 100644 --- a/Assets/Scripts/ServerShared/StationWants.cs +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -15,7 +15,13 @@ using Newtonsoft.Json; // product's MaxStack (a good a haul order names has a share of the silo as a product has). A recipe starts only when its product has room (CanStart), and a station draws an ore only while some recipe // that takes it can start, so a full product stops its ores being bought while the station keeps running its other recipes. Prior // art: X4's per-ware storage allocation (a full ware stops that production, the station keeps running the rest) and Factorio's -// per-product output slot. A station with no silo has no bound: outputs land in any bay and Room happens at the put. +// per-product output slot. A station with no silo has no bound on outputs: they land in any bay and Room happens at the put. +// +// How much of a drawn good a station holds (ruling stations-buy-ingredients-to-target-share): the other half of the same division of +// the hold. The stock bays' cells are shared among the ingredients of the installed recipes in proportion to the rate the facilities +// consume them (Holding), so no one ingredient arriving first can fill the bays and starve its partners; each stops being wanted at +// its share. Prior art: X4 allots storage per ware for what a station buys as for what it makes, and an order-up-to level per input +// is the inventory-control form of a cap on each input. Allocation is the output side, Holding the input side. public static class StationWants { public static IReadOnlyCollection Of(Entity station) @@ -25,16 +31,18 @@ public static class StationWants return wants; } - // Where a bought or delivered good may land and how much of it: the non-silo bays, unbounded, when an installed recipe facility - // draws it (a drawn good is stock, never silo content); the silo bays, up to the good's share of the silo (Room), when the station - // wants it through a haul order (a transit depot holds goods in its silo, never in its stock bay). The one owner of where a good - // lands; none when the station does not want it. + // Where a bought or delivered good may land and how much of it: the non-silo bays, up to the good's Holding less what the station + // holds of it, when an installed recipe facility draws it (a drawn good is stock, never silo content); the silo bays, up to the + // good's share of the silo (Room), when the station wants it through a haul order (a transit depot holds goods in its silo, never + // in its stock bay). The one owner of where a good lands and how much; none when the station does not want it. public static IEnumerable<(IReadOnlyList Bays, int Room)> Landing(Entity station, CultRecordKey good) => - LandingOf(station, Drawn(station), Ordered(station).ToHashSet(), good); + LandingOf(station, Drawn(station), Holding(station), Ordered(station).ToHashSet(), good); - private static IEnumerable<(IReadOnlyList Bays, int Room)> LandingOf(Entity station, HashSet drawn, HashSet ordered, CultRecordKey good) + private static IEnumerable<(IReadOnlyList Bays, int Room)> LandingOf(Entity station, HashSet drawn, + IReadOnlyDictionary holding, HashSet ordered, CultRecordKey good) { - if (drawn.Contains(good)) yield return (station.CargoBays.Where(bay => !(bay.Data is SiloData)).ToArray(), int.MaxValue); + if (drawn.Contains(good)) + yield return (station.CargoBays.Where(bay => !(bay.Data is SiloData)).ToArray(), Math.Max(0, holding[good] - station.CargoBays.Sum(bay => bay.Count(good)))); if (ordered.Contains(good)) yield return (station.CargoBays.Where(bay => bay.Data is SiloData).ToArray(), Room(station, good)); } @@ -43,8 +51,9 @@ public static class StationWants public static HashSet Takable(Entity station, IEnumerable goods) { var drawn = Drawn(station); + var holding = Holding(station); var ordered = Ordered(station).ToHashSet(); - return goods.Where(good => LandingOf(station, drawn, ordered, good).Any(landing => landing.Room > 0 + return goods.Where(good => LandingOf(station, drawn, holding, ordered, good).Any(landing => landing.Room > 0 && landing.Bays.Any(bay => bay.TryFindSpace(new SimpleCommodity { Data = new CultRecordRef(good), Quantity = 1 })))).ToHashSet(); } @@ -82,17 +91,19 @@ public static class StationWants // Whether the recipe's product has room for one more cycle's output. public static bool CanStart(Entity station, RecipeData recipe) => Room(station, recipe.Output.Key) >= recipe.OutputCount; - private static IEnumerable FacilityRecipes(Entity station) + // The run list of each installed recipe facility unit: two units of one design are two lists. + private static IEnumerable> FacilityRuns(Entity station) { var catalog = station.ItemManager.ItemData; 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)) yield return recipe; + if (StationKinds.IsRecipeFacility(design)) yield return Production.RunList(catalog, catalog.RefOf(design).Key); } } + private static IEnumerable FacilityRecipes(Entity station) => FacilityRuns(station).SelectMany(run => run); + // Every good the station's installed recipe facilities consume, startable or not: what a standing haul order may carry to it (a // seeded leg waits on room and never writes an order for a good no installed recipe takes). The crew's table is not here: it is // bought by sale, never hauled by a seeded leg. Drawn is the startable part. @@ -109,14 +120,59 @@ public static class StationWants foreach (var recipe in FacilityRecipes(station).Where(recipe => CanStart(station, recipe))) foreach (var draw in Production.Draws(catalog, recipe)) wants.Add(draw); - // What its crew eats: the table of every habitation unit that runs (the module defines what and how much it consumes). - foreach (var unit in station.Equipment.Where(unit => unit.Enabled.Value && !unit.EquippableItem.IsDestroyed)) - foreach (var habitation in unit.Behaviors.Select(behavior => behavior.Data).OfType()) - foreach (var row in habitation.Table.Where(row => row.Commodity.IsSet())) - wants.Add(row.Commodity.Key); + wants.UnionWith(Crew(station)); return wants; } + // What its crew eats: the table of every habitation unit that runs (the module defines what and how much it consumes). + private static IEnumerable Crew(Entity station) => + station.Equipment.Where(unit => unit.Enabled.Value && !unit.EquippableItem.IsDestroyed) + .SelectMany(unit => unit.Behaviors.Select(behavior => behavior.Data).OfType()) + .SelectMany(habitation => habitation.Table.Where(row => row.Commodity.IsSet()).Select(row => row.Commodity.Key)); + + // The share of the stock bays' cells that the facility ingredients may fill together: a balance knob (ruling + // economy-numbers-are-sim-tuned-knobs), beside LoadoutGenerator.StationStockShare, which is the gear stock's. + public const float IngredientShare = 1.0f; + + // The units of each drawn good the station will hold, the input side of the division of the hold. Every installed recipe facility + // unit consumes round-robin over its run list, so each slot of each recipe (an Input, an Upkeep, a role) is taken at count / (sum of + // the list's cycles); a role slot is taken from any one of its fillers, so each filler may fill the whole slot. W is the sum of the + // slot rates, and a good holds IngredientShare of the stock cells in MaxStack units, times the part of W its slots carry, never + // less than the largest count of a slot it fills (one cycle can always start). A good only the crew's table names holds one stack. + // Derived on every call, stored nowhere: a facility removed takes its shares with it. Held is counted over every bay, so a product + // the station also consumes counts toward its share, and stock above a share is kept (Room reads 0), never removed. + public static IReadOnlyDictionary Holding(Entity station) + { + var catalog = station.ItemManager.ItemData; + var slots = new List<(double Rate, int Count, IReadOnlyCollection Goods)>(); + foreach (var run in FacilityRuns(station)) + { + var cycles = run.Sum(recipe => (double) recipe.Cycle); + if (cycles <= 0) continue; + foreach (var recipe in run) + { + foreach (var input in recipe.Inputs.Concat(recipe.Upkeep)) + slots.Add((input.Count / cycles, input.Count, new[] { input.Commodity.Key })); + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + slots.Add((role.Count / cycles, role.Count, Recipes.Fillers(catalog, role.Name))); + } + } + var cells = station.CargoBays.Where(bay => !(bay.Data is SiloData)).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); + var total = slots.Sum(slot => slot.Rate); + var holding = new Dictionary(); + int Stack(CultRecordKey good) => catalog.Get(good)?.MaxStack ?? 1; + foreach (var good in slots.SelectMany(slot => slot.Goods).Distinct()) + { + var fills = slots.Where(slot => slot.Goods.Contains(good)).ToArray(); + // The share is a ratio of whole numbers: a quotient that is 8 to the last digit must not floor to 7. + var share = (int) Math.Floor(IngredientShare * cells * Stack(good) * fills.Sum(slot => slot.Rate) / total + 1e-9); + holding[good] = Math.Max(share, fills.Max(slot => slot.Count)); + } + foreach (var good in Crew(station)) + if (!holding.ContainsKey(good)) holding[good] = Stack(good); + return holding; + } + private static IEnumerable Ordered(Entity station) { if (!(station is OrbitalEntity { OrbitData: var orbit }) || !orbit.IsSet() || !station.CargoBays.Any(bay => bay.Data is SiloData)) diff --git a/tests/Aetheria.Shared.Tests/StationWantsTests.cs b/tests/Aetheria.Shared.Tests/StationWantsTests.cs index deec6339a..adfe74b08 100644 --- a/tests/Aetheria.Shared.Tests/StationWantsTests.cs +++ b/tests/Aetheria.Shared.Tests/StationWantsTests.cs @@ -247,4 +247,284 @@ public sealed partial class RunStartTests } } } + + // What a station buys to hold (aetheria-living-world, cut stationwants-ingredient-share; ruling stations-buy-ingredients-to-target-share): + // each ingredient of the installed recipes stops at its share of the stock bays, split by the rate its slots are consumed at. + private CultRecordKey GoodNamed(string name) => _cache.RefOf(_cache.GetAll().Single(data => data.Name == name)).Key; + + private int MaxStack(CultRecordKey good) => _cache.Get(good).MaxStack; + + // Every slot of the station's recipe facilities, read again from the catalog and not from StationWants: its rate (count over the sum of the + // run list's cycles), its count and the goods that fill it. + private List<(double Rate, int Count, CultRecordKey[] Goods)> SlotsOf(Entity station) + { + var slots = new List<(double, int, CultRecordKey[])>(); + foreach (var unit in station.Equipment) + { + var design = _items.GetData(unit.EquippableItem); + if (!StationKinds.IsRecipeFacility(design)) continue; + var run = Production.RunList(_cache, _cache.RefOf(design).Key); + var cycles = run.Sum(recipe => (double) recipe.Cycle); + foreach (var recipe in run) + { + foreach (var input in recipe.Inputs) slots.Add((input.Count / cycles, input.Count, new[] { input.Commodity.Key })); + foreach (var upkeep in recipe.Upkeep) slots.Add((upkeep.Count / cycles, upkeep.Count, new[] { upkeep.Commodity.Key })); + foreach (var role in Recipes.RoleInputsOf(_cache, recipe)) slots.Add((role.Count / cycles, role.Count, Recipes.Fillers(_cache, role.Name))); + } + } + return slots; + } + + // A ratio of whole numbers that is 8 to the last digit floors to 8. + private static int Floored(double share) => (int) Math.Floor(share + 1e-9); + + private static int StockCells(Entity station) => + station.CargoBays.Where(bay => !(bay.Data is SiloData)).Sum(bay => bay.Data.InteriorShape.Coordinates.Length); + + // The proportional share of a good before the floor, from the slots read above. + private double Proportional(Entity station, List<(double Rate, int Count, CultRecordKey[] Goods)> slots, CultRecordKey good) => + StationWants.IngredientShare * StockCells(station) * MaxStack(good) * slots.Where(slot => slot.Goods.Contains(good)).Sum(slot => slot.Rate) / slots.Sum(slot => slot.Rate); + + // Puts exactly `units` of the good in the station's stock bays, after taking out what is there. + private static void Hold(Entity station, CultRecordKey good, int units) + { + foreach (var bay in station.CargoBays.Where(bay => !(bay.Data is SiloData))) + foreach (var stack in bay.Cargo.Keys.Where(stack => stack is SimpleCommodity held && held.Data.Key.Equals(good)).ToArray()) + bay.Remove(stack); + for (var left = units; left > 0; left -= 10) + Assert.True(station.CargoBays.Where(bay => !(bay.Data is SiloData)).Any(bay => bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(good), Quantity = Math.Min(10, left) }))); + Assert.Equal(units, station.CargoBays.Sum(bay => bay.Count(good))); + } + + // Sells `units` of the good from the player's hold, a stack at a time, and returns the units that went across. + private int SoldFrom(EquippedCargoBay hold, Entity station, CultRecordKey good, int units) + { + var credits = 0; + var sold = 0; + for (var left = units; left > 0; left -= 10) + { + var offered = new SimpleCommodity { Data = new CultRecordRef(good), Quantity = Math.Min(10, left) }; + if (!hold.TryStore(offered)) break; + sold += StationServices.TrySellPart(hold, station, offered, ref credits).Sold; + } + return sold; + } + + // Eighty of one input stop at its share, so one ore arriving first cannot fill the bay and starve its partners: the rest stays with the + // seller and the partner is still taken. + [Fact] + public void AnIngredientStopsAtItsShare() + { + var (_, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var refinery = StationOfKind(arena, "processing"); + var regolith = GoodNamed("Regolith"); + var partner = GoodNamed("Nickel-Iron"); + var share = StationWants.Holding(refinery)[regolith]; + Assert.InRange(share, 1, 79); + var held = refinery.CargoBays.Sum(bay => bay.Count(regolith)); + var hold = staged.Player.CargoBays[0]; + var sold = SoldFrom(hold, refinery, regolith, 80); + Assert.Equal(Math.Max(0, share - held), sold); + Assert.Equal(80 - sold, hold.Count(regolith)); + Assert.Contains(partner, StationWants.Takable(refinery, new[] { regolith, partner })); + Assert.DoesNotContain(regolith, StationWants.Takable(refinery, new[] { regolith, partner })); + var credits = 0; + var left = hold.Cargo.Keys.OfType().First(stack => ((ItemInstance) stack).Data.Key.Equals(regolith)); + Assert.Equal(SaleRefusal.NoRoom, StationServices.TrySellPart(hold, refinery, left, ref credits).Refusal); + } + + // The split is by the rate the installed recipes consume each slot at: every drawn good holds its slots' part of the stock cells, so the + // iron ore Steel takes three to one over the other inputs holds three times what they do, and the two metal roles add their fillers' slots. + [Fact] + public void TheShareFollowsTheRecipesSlots() + { + var refinery = DemoStation("processing"); + var slots = SlotsOf(refinery); + var holding = StationWants.Holding(refinery); + Assert.Equal(slots.SelectMany(slot => slot.Goods).Distinct().OrderBy(good => good.Value, StringComparer.Ordinal), holding.Keys.OrderBy(good => good.Value, StringComparer.Ordinal)); + foreach (var good in holding.Keys) + { + var count = slots.Where(slot => slot.Goods.Contains(good)).Max(slot => slot.Count); + Assert.Equal(Math.Max(Floored(Proportional(refinery, slots, good)), count), holding[good]); + } + // Two goods whose shares are above their floors hold units in the ratio of their slot rates, to a unit of rounding. + var free = holding.Keys.Where(good => Floored(Proportional(refinery, slots, good)) > slots.Where(slot => slot.Goods.Contains(good)).Max(slot => slot.Count)).ToArray(); + Assert.True(free.Length >= 2, $"{free.Length} goods above their floor"); + var most = free.OrderByDescending(good => Proportional(refinery, slots, good)).First(); + var least = free.OrderBy(good => Proportional(refinery, slots, good)).First(); + Assert.True(Proportional(refinery, slots, most) > 1.5 * Proportional(refinery, slots, least), "the split is not even"); + Assert.True(holding[most] > holding[least]); + } + + // A role slot may be filled by any one of its fillers, so each filler may fill the whole slot: the fillers of a role that fill nothing + // else all hold the slot's own share. + [Fact] + public void ARoleFillerHoldsItsRolesShare() + { + var refinery = DemoStation("processing"); + var slots = SlotsOf(refinery); + var holding = StationWants.Holding(refinery); + var checkedRoles = 0; + foreach (var slot in slots.Where(slot => slot.Goods.Length > 1)) + { + var alone = slot.Goods.Where(good => slots.Count(other => other.Goods.Contains(good)) == 1).ToArray(); + if (alone.Length < 2) continue; + checkedRoles++; + var own = Math.Max(Floored(StationWants.IngredientShare * StockCells(refinery) * MaxStack(alone[0]) * slot.Rate / slots.Sum(other => other.Rate)), slot.Count); + Assert.All(alone, good => Assert.Equal(own, holding[good])); + } + Assert.True(checkedRoles > 0, "no role slot has two fillers that fill nothing else"); + } + + // Every slot can start a cycle: a good holds at least the most any slot it fills takes. No shipped facility has enough slots to push a + // proportional share under one cycle, so the catalog is edited (a recipe gains an input of 400 units a cycle) until some slots do. + [Fact] + public void AShareIsAtLeastOneCycle() + { + var refinery = DemoStation("processing"); + void Holds(bool floorBinds) + { + var slots = SlotsOf(refinery); + var holding = StationWants.Holding(refinery); + var floored = 0; + foreach (var good in holding.Keys) + { + var count = slots.Where(slot => slot.Goods.Contains(good)).Max(slot => slot.Count); + Assert.True(holding[good] >= count, $"{_cache.Get(good).Name}: {holding[good]} held for a slot of {count}"); + if (Floored(Proportional(refinery, slots, good)) < count) + { + floored++; + Assert.Equal(count, holding[good]); + } + } + Assert.Equal(floorBinds, floored > 0); + } + Holds(floorBinds: false); + + var design = refinery.Equipment.Select(unit => _items.GetData(unit.EquippableItem)).Single(data => StationKinds.IsRecipeFacility(data)); + var recipe = Production.RunList(_cache, _cache.RefOf(design).Key).First(candidate => candidate.Inputs.Count > 0); + var ballast = GoodNamed("Regolith"); + recipe.Inputs.Add(new CommodityCount { Commodity = new CultRecordRef(ballast), Count = 400 }); + _cache.Upsert(typeof(RecipeData), recipe, RecipeData.KeyOf(recipe.Output.Key)); + Holds(floorBinds: true); + } + + // One cap for every buyer: at its share a good is refused by the player's sale, the ore sale, a hauler's delivery and the hauler's door + // test; one unit below the share each moves exactly one. + [Fact] + public void SaleAndDeliveryStopAtOneCap() + { + var world = HaulStage(silo: 0); + var station = world.Refinery; + var good = world.Good; + var share = StationWants.Holding(station)[good]; + Assert.InRange(share, 2, 70); + var hold = world.Player.CargoBays[0]; + var credits = 0; + void Carry(EquippedCargoBay bay, int units) + { + foreach (var stack in bay.Cargo.Keys.ToArray()) bay.Remove(stack); + Assert.True(bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(good), Quantity = units })); + } + int ByPlayer() + { + Carry(hold, 1); + return StationServices.TrySellPart(hold, station, hold.Cargo.Keys.OfType().Single(), ref credits).Sold; + } + int ByOreSale() + { + Carry(hold, 1); + return StationServices.TrySellOre(new[] { hold }, station, ref credits).Sold; + } + int ByHauler() + { + Carry(world.Hauler.CargoBays[0], 1); + world.Hauler.HaulSeen = null; + HaulRun.Call(world.Hauler, station); + return 1 - Units(world.Hauler.CargoBays, good); + } + var buyers = new (string Name, Func Sell)[] { ("player", ByPlayer), ("ore sale", ByOreSale), ("hauler", ByHauler) }; + + Hold(station, good, share); + Assert.DoesNotContain(good, StationWants.Takable(station, new[] { good })); + foreach (var (name, sell) in buyers) + { + Assert.Equal(0, sell()); + Assert.True(share == Units(station.CargoBays, good), $"{name} stored past the share"); + } + foreach (var (name, sell) in buyers) + { + Hold(station, good, share - 1); + Assert.Contains(good, StationWants.Takable(station, new[] { good })); + Assert.True(1 == sell(), $"{name} moved other than one unit below the share"); + Assert.Equal(share, Units(station.CargoBays, good)); + } + } + + // Stock above its share is kept, never removed: a sale and a facility's own working leave it, the station refuses more, and the room + // reads nothing rather than less than nothing. + [Fact] + public void StockAboveItsShareIsKeptAndRefused() + { + var world = HaulStage(silo: 0); + var station = world.Refinery; + var good = world.Good; + var share = StationWants.Holding(station)[good]; + var over = share + 8; + Hold(station, good, over); + Assert.Equal(over, Units(station.CargoBays, good)); + Assert.DoesNotContain(good, StationWants.Takable(station, new[] { good })); + Assert.Equal(0, StationWants.Landing(station, good).Sum(landing => landing.Room)); + Assert.Equal(0, SoldFrom(world.Player.CargoBays[0], station, good, 10)); + Assert.Equal(over, Units(station.CargoBays, good)); + Assert.Equal(SaleRefusal.NoRoom, SaleRefusalOf(world.Player.CargoBays[0], station, good)); + } + + private SaleRefusal SaleRefusalOf(EquippedCargoBay hold, Entity station, CultRecordKey good) + { + var credits = 0; + var offered = new SimpleCommodity { Data = new CultRecordRef(good), Quantity = 1 }; + Assert.True(hold.TryStore(offered)); + return StationServices.TrySellPart(hold, station, offered, ref credits).Refusal; + } + + // No drawn good is unbounded: a station whose only drawing gear is its crew's quarters holds one stack of each good of the table. + [Fact] + public void ACrewOnlyGoodHoldsOneStack() + { + var zenith = DemoStation("trade-hub"); + Assert.DoesNotContain(zenith.Equipment, unit => StationKinds.IsRecipeFacility(_items.GetData(unit.EquippableItem))); + var crew = zenith.Equipment.SelectMany(unit => unit.Behaviors.Select(behavior => behavior.Data).OfType()).SelectMany(data => data.Table.Select(row => row.Commodity.Key)).Distinct().ToArray(); + Assert.NotEmpty(crew); + var holding = StationWants.Holding(zenith); + Assert.Equal(crew.OrderBy(good => good.Value, StringComparer.Ordinal), holding.Keys.OrderBy(good => good.Value, StringComparer.Ordinal)); + foreach (var good in crew) + { + Assert.Equal(MaxStack(good), holding[good]); + Hold(zenith, good, MaxStack(good)); + Assert.Equal(0, StationWants.Landing(zenith, good).Sum(landing => landing.Room)); + Assert.DoesNotContain(good, StationWants.Takable(zenith, new[] { good })); + Hold(zenith, good, 0); + } + } + + // What a station will hold is read from the gear installed on it at every call: take the refinery unit off a copy and the shares of what only it + // consumed are gone, and the original, never written to, reads as it did. + [Fact] + public void HoldingFollowsInstalledFacilities() + { + var refinery = DemoStation("processing"); + var before = StationWants.Holding(refinery).ToDictionary(kv => kv.Key, kv => kv.Value); + Assert.NotEmpty(before); + var copy = (OrbitalEntity) EntitySerializer.Unpack(_items, refinery.Zone, EntitySerializer.Pack(refinery)); + Assert.Equal(before.OrderBy(kv => kv.Key.Value, StringComparer.Ordinal), StationWants.Holding(copy).OrderBy(kv => kv.Key.Value, StringComparer.Ordinal)); + var facilities = copy.Equipment.Where(unit => StationKinds.IsRecipeFacility(_items.GetData(unit.EquippableItem))).ToArray(); + Assert.NotEmpty(facilities); + var crew = copy.Equipment.SelectMany(unit => unit.Behaviors.Select(behavior => behavior.Data).OfType()).SelectMany(data => data.Table.Select(row => row.Commodity.Key)).ToHashSet(); + foreach (var unit in facilities) Assert.NotNull(copy.TryUnequip(unit)); + var after = StationWants.Holding(copy); + Assert.All(before.Keys.Where(good => !crew.Contains(good)), good => Assert.False(after.ContainsKey(good))); + Assert.Equal(before.OrderBy(kv => kv.Key.Value, StringComparer.Ordinal), StationWants.Holding(refinery).OrderBy(kv => kv.Key.Value, StringComparer.Ordinal)); + } } diff --git a/tools/AetherDb/EconomyRegion.cs b/tools/AetherDb/EconomyRegion.cs index 6ed8a196c..ce5a09f02 100644 --- a/tools/AetherDb/EconomyRegion.cs +++ b/tools/AetherDb/EconomyRegion.cs @@ -33,6 +33,8 @@ public sealed class RegionStation public List Facilities = new List(); // Units held of each good any facility here makes, at the start and at the end of the horizon. public SortedDictionary Held = new SortedDictionary(StringComparer.Ordinal); + // Units held at the end of each good the station draws (every bay) and the units it will hold of it (StationWants.Holding). + public SortedDictionary Inputs = new SortedDictionary(StringComparer.Ordinal); } // One (faction, kind) of the region's non-entrance stations: how many, and the depth toward the gate they sit at. @@ -205,6 +207,12 @@ public static class EconomyRegion var name = Good(tracked[s].outputs[o]); tracked[s].station.Held[name] = (tracked[s].station.Held[name].Start, heldLast[s][o]); } + foreach (var (station, entity, _, _) in tracked) + { + var end = new EntityHold(entity); + foreach (var (good, holding) in StationWants.Holding(entity)) + station.Inputs[Good(good)] = (end.Held(good), holding); + } foreach (var recipe in sample.Recipes) { recipe.Made = made.TryGetValue(recipe.Output, out var units) ? units : 0; @@ -308,6 +316,8 @@ public static class EconomyRegion output.WriteLine($" facility {facility.Name}: {(total == 0 ? "no spans" : string.Join(", ", facility.Stalls.Select(kv => string.Format(inv, "{0} {1:0.#}%", kv.Key, 100.0 * kv.Value / total))))}"); } output.WriteLine(" held at start -> end: " + string.Join("; ", station.Held.Select(kv => $"{kv.Key} {kv.Value.Start} -> {kv.Value.End}"))); + var inputs = station.Inputs.Where(kv => kv.Value.Held > 0).ToArray(); + if (inputs.Length > 0) output.WriteLine(" inputs held at end: " + string.Join("; ", inputs.Select(kv => $"{kv.Key} {kv.Value.Held}/{kv.Value.Holding}"))); } output.WriteLine(" recipes of the facilities the region holds (output | facilities | made: a lower bound, at least N from held-unit rises, so a unit another recipe takes in the same span is missed | ran | facility ends | cycle)"); foreach (var recipe in sample.Recipes.OrderBy(r => r.Output, StringComparer.Ordinal))