diff --git a/Assets/Scripts/ServerShared/HaulRun.cs b/Assets/Scripts/ServerShared/HaulRun.cs index 16e95290a..1240fa62e 100644 --- a/Assets/Scripts/ServerShared/HaulRun.cs +++ b/Assets/Scripts/ServerShared/HaulRun.cs @@ -33,7 +33,7 @@ public static class HaulRun return station.CargoBays.Where(bay => bay.Data is SiloData).SelectMany(bay => bay.Cargo.Keys).OfType() .Any(stack => Goods(order).Contains(((ItemInstance) stack).Data.Key) && ship.CargoBays.Any(bay => bay.TryFindSpace(stack.Split(1)))); if (orbit.Equals(order.To.Key)) - return Carried(ship, order).Any(stack => StationWants.Bays(station, ((ItemInstance) stack).Data.Key).Any(bay => bay.TryFindSpace(stack.Split(1)))); + return Carried(ship, order).Any(stack => StationWants.Landing(station, ((ItemInstance) stack).Data.Key).Any(landing => landing.Room > 0 && landing.Bays.Any(bay => bay.TryFindSpace(stack.Split(1))))); return false; } diff --git a/Assets/Scripts/ServerShared/Production.cs b/Assets/Scripts/ServerShared/Production.cs index 40fe32e23..19071bf31 100644 --- a/Assets/Scripts/ServerShared/Production.cs +++ b/Assets/Scripts/ServerShared/Production.cs @@ -196,12 +196,8 @@ public sealed class EntityHold : IProductionHold return true; } - // The units the output bays may still take of the design: the station's allocation less what they hold, unbounded without one. - public int Room(CultRecordKey design) - { - var allocation = StationWants.Allocation(_entity, design); - return allocation == null ? int.MaxValue : Math.Max(0, allocation.Value - StationWants.OutputBays(_entity, design).Sum(bay => bay.Count(design))); - } + // The units the output bays may still take of the design (StationWants.Room, the one decision of room). + public int Room(CultRecordKey design) => StationWants.Room(_entity, design); public bool TryPut(CultRecordKey design, int units) { diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index 3af42a483..356989eec 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -135,7 +135,9 @@ public static class StationServices 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 stored = MoveParts(from, StationWants.Bays(station, item.Data.Key).ToArray(), stack, moved); + var stored = 0; + foreach (var (bays, room) in StationWants.Landing(station, item.Data.Key).ToArray()) + stored += MoveParts(from, bays, stack, moved, room); return new SaleResult(stored, offered, stored < offered ? SaleRefusal.NoRoom : SaleRefusal.None); } @@ -152,11 +154,11 @@ public static class StationServices } // Moves the stack into the bays, the whole quantity first and then fewer, until nothing more fits: the units moved. - private static int MoveParts(EquippedCargoBay from, IReadOnlyCollection into, ICommodityStack stack, Action moved) + private static int MoveParts(EquippedCargoBay from, IReadOnlyCollection into, ICommodityStack stack, Action moved, int limit = int.MaxValue) { var item = (ItemInstance) stack; var total = 0; - var remaining = stack.Quantity; + var remaining = Math.Min(stack.Quantity, limit); while (remaining > 0) { var count = 0; diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs index 521ab061f..e7743b3c1 100644 --- a/Assets/Scripts/ServerShared/StationWants.cs +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using GameCult.Caching; @@ -11,7 +12,7 @@ using Newtonsoft.Json; // // Where goods land and how much of a product a station holds (cut facility-output-room). A station with a silo keeps what its // facilities make there, and each product holds an even share of the silo: Allocation, floor(silo cells / products) x the -// product's MaxStack. A recipe starts only when its product has room (CanStart), and a station draws an ore only while some recipe +// 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. @@ -24,42 +25,49 @@ public static class StationWants return wants; } - // The bays a bought or delivered good may land in: the non-silo bays when an installed recipe facility draws it (a drawn good - // is stock, never silo content), the silo bays 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. - public static IEnumerable Bays(Entity station, CultRecordKey good) + // 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. + public static IEnumerable<(IReadOnlyList Bays, int Room)> Landing(Entity station, CultRecordKey good) { - var bays = Enumerable.Empty(); - if (Drawn(station).Contains(good)) bays = bays.Concat(station.CargoBays.Where(bay => !(bay.Data is SiloData))); - if (Ordered(station).Contains(good)) bays = bays.Concat(station.CargoBays.Where(bay => bay.Data is SiloData)); - return bays; + if (Drawn(station).Contains(good)) yield return (station.CargoBays.Where(bay => !(bay.Data is SiloData)).ToArray(), int.MaxValue); + if (Ordered(station).Contains(good)) yield return (station.CargoBays.Where(bay => bay.Data is SiloData).ToArray(), Room(station, good)); } + public static IEnumerable Bays(Entity station, CultRecordKey good) => Landing(station, good).SelectMany(landing => landing.Bays); + // The bays a facility's output may land in: the silo bays when the station has one, else every bay. The one owner of where // a facility output lands. public static IEnumerable OutputBays(Entity station, CultRecordKey good) => station.CargoBays.Any(bay => bay.Data is SiloData) ? station.CargoBays.Where(bay => bay.Data is SiloData) : station.CargoBays; - // The units of a product the station may hold in its output bays: the silo's cells divided evenly among the distinct outputs of - // its recipe facilities, each share worth that many full stacks of the product. Null (no bound) without a silo or a recipe - // facility. Derived on every call, stored nowhere. - public static int? Allocation(Entity station, CultRecordKey product) + // The units of a good the station may hold in its silo: the silo's cells divided evenly among the distinct goods that land there, + // the outputs of its recipe facilities and the goods of its haul orders, each share worth that many full stacks of the good. Null + // (no bound) without a silo or a recipe facility (a depot with no facility holds what its orders name). Derived on every call, + // stored nowhere. + public static int? Allocation(Entity station, CultRecordKey good) { var silos = station.CargoBays.Where(bay => bay.Data is SiloData).ToArray(); if (silos.Length == 0) return null; - var products = FacilityRecipes(station).Select(recipe => recipe.Output.Key).Distinct().Count(); - if (products == 0) return null; + var outputs = FacilityRecipes(station).Select(recipe => recipe.Output.Key).ToArray(); + if (outputs.Length == 0) return null; + var slots = outputs.Concat(Ordered(station)).Distinct().Count(); var cells = silos.Sum(bay => bay.Data.InteriorShape.Coordinates.Length); - var stack = station.ItemManager.ItemData.Get(product)?.MaxStack ?? 0; - return cells / products * stack; + var stack = station.ItemManager.ItemData.Get(good)?.MaxStack ?? 0; + return cells / slots * stack; + } + + // The units of a good that may still be stored in the silo: its share less what the output bays hold, int.MaxValue with no bound. + // The one decision of room: a recipe starts on it (CanStart, EntityHold.Room) and a sale of an ordered good stops at it. + public static int Room(Entity station, CultRecordKey good) + { + var allocation = Allocation(station, good); + return allocation == null ? int.MaxValue : Math.Max(0, allocation.Value - OutputBays(station, good).Sum(bay => bay.Count(good))); } // Whether the recipe's product has room for one more cycle's output. - public static bool CanStart(Entity station, RecipeData recipe) - { - var allocation = Allocation(station, recipe.Output.Key); - return allocation == null || OutputBays(station, recipe.Output.Key).Sum(bay => bay.Count(recipe.Output.Key)) + recipe.OutputCount <= allocation; - } + public static bool CanStart(Entity station, RecipeData recipe) => Room(station, recipe.Output.Key) >= recipe.OutputCount; private static IEnumerable FacilityRecipes(Entity station) { diff --git a/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs b/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs index deb2f7403..32f184fd1 100644 --- a/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs @@ -149,6 +149,27 @@ public sealed class EconomyDrainTests Assert.Contains("Room", fault.Message); } + // Without outflow a supplied refinery saturates: products reach their share, the ores of full products are no longer bought, and the station + // ends Room-stalled with ore it cannot use. The harness names it, so the region work that adds outflow is measured against it. + [Fact] + public void ASaturatedRefineryIsNamed() + { + var supplied = EconomyDrain.Run(Root, 1, 30, 24, Seed1.Value, supplied: true); + var refinery = Station(supplied, "processing"); + Assert.NotNull(refinery.FirstSaturated); + Assert.True(refinery.WantedEnd < refinery.WantedStart); + Assert.Equal(Stall.Room, refinery.Facilities.Single().HorizonEnd); + Assert.NotEmpty(refinery.Facilities.Single().Saturated); + var fault = Assert.Single(EconomyDrain.Report(new[] { supplied }), f => f.Invariant == EconomyDrain.HSaturated); + Assert.Contains("nothing taking them out", fault.Message); + Assert.DoesNotContain(EconomyDrain.Report(new[] { supplied }), f => f.Invariant == EconomyDrain.HStall && f.Record.EndsWith("processing")); + + // One fill, no supply: nothing saturates, and the report names none. + var once = EconomyDrain.Run(Root, 1, 30, 24, Seed1.Value); + Assert.Null(Station(once, "processing").FirstSaturated); + Assert.DoesNotContain(EconomyDrain.Report(new[] { once }), f => f.Invariant == EconomyDrain.HSaturated); + } + // A sortie the base loop faults is a fault of its own and no sortie of the fill count (Soul s1, fill-count-artifact). [Fact] public void AFaultedSortieIsReportedAndLeftOutOfTheFill() diff --git a/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs b/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs index 4a094eb3a..07999eb4b 100644 --- a/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs +++ b/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs @@ -56,12 +56,14 @@ public sealed class FacilityProductionTests : IDisposable Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = Solid(2, 2), Transform = "Fa.1" }, - new HardpointData { Type = HardpointType.Facility, Position = new int2(2, 0), Shape = Solid(2, 2), Transform = "Fa.2" } + new HardpointData { Type = HardpointType.Facility, Position = new int2(2, 0), Shape = Solid(2, 2), Transform = "Fa.2" }, + new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 2), Shape = Solid(2, 2), Transform = "Fa.3" } } }); cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Price = 20, Durability = 4 }); cache.Upsert(new CargoBayData { Name = "Pocket", Shape = new Shape(), InteriorShape = Solid(1, 1), Price = 5, Durability = 4 }); cache.Upsert(new SimpleCommodityData { Name = "Slag", Shape = new Shape(), Price = 1, MaxStack = 100 }); + cache.Upsert(new GearData { Name = "Lamp", Shape = Solid(1, 1), Price = 1, Durability = 4, Hardpoint = HardpointType.Tool }); cache.Upsert(new ConsumableItemData { Name = "Facility Pill", Shape = new Shape(), Price = 1, Behaviors = { new FacilityData() } }); } @@ -87,7 +89,7 @@ public sealed class FacilityProductionTests : IDisposable } // A station of Test Yard with the named facility on its row and the named bay, and the shipped silo on its second row when asked. - private World Build(string facility = "Refinery", string bay = "Crate", bool silo = false) + private World Build(string facility = "Refinery", string bay = "Crate", bool silo = false, bool twin = false) { var items = new ItemManager(1u, _cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); @@ -95,13 +97,14 @@ public sealed class FacilityProductionTests : IDisposable Assert.True(station.TryEquip(Mint(items, _cache, facility), new int2(0, 0))); Assert.True(station.TryEquip(Mint(items, _cache, bay), new int2(4, 4))); if (silo) Assert.True(station.TryEquip(Mint(items, _cache, "Silo"), new int2(2, 0))); + if (twin) Assert.True(station.TryEquip(Mint(items, _cache, facility), new int2(0, 2))); zone.Admit(station, piloted: false); return Wrap(items, zone, station); } private static World Wrap(ItemManager items, Zone zone, OrbitalEntity station) { - var item = station.Equipment.Single(equipped => equipped.Behaviors.Any(behavior => behavior is Facility)); + var item = station.Equipment.First(equipped => equipped.Behaviors.Any(behavior => behavior is Facility)); return new World { Items = items, Zone = zone, Station = station, Facility = item.Behaviors.OfType().Single(), @@ -376,6 +379,42 @@ public sealed class FacilityProductionTests : IDisposable Assert.True(StationWants.CanStart(world.Station, _cache.Get(RecipeData.KeyOf(Iron)))); } + [Fact] + public void AStartNeedsAWholeCycleOfRoom() + { + var world = Build(silo: true); + var cycle = _cache.Get(RecipeData.KeyOf(Iron)).OutputCount; + Assert.True(cycle > 1); + Assert.True(world.Hold.TryPut(Iron, ShareOf(Iron) - cycle + 1)); + Assert.Equal(cycle - 1, world.Hold.Room(Iron)); + Stock(world, IronFillers[0], 3); + Assert.Equal(Stall.Room, Production.Advance(_cache, RefineryRuns, null, 1, world.Hold).stall); + Assert.Equal(3, Held(world, IronFillers[0])); + Assert.True(world.Hold.TryTake(new[] { (Iron, 1) })); + Assert.Equal(Stall.None, Production.Advance(_cache, RefineryRuns, null, 1, world.Hold).stall); + Assert.Equal(0, Held(world, IronFillers[0])); + } + + [Fact] + public void TwoFacilitiesOfOneKindShareTheirProducts() + { + var world = Build(silo: true, twin: true); + Assert.Equal(ShareOf(Iron), StationWants.Allocation(world.Station, Iron)); + } + + [Fact] + public void GeneralGearNeverTakesAFacilityRow() + { + var items = new ItemManager(1u, _cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = new OrbitalEntity(items, zone, Mint(items, _cache, "Test Yard"), default, new EntitySettings()); + // Fa.2 is empty: a lamp is refused there, taken beside it, and the row is not free space. + Assert.False(station.TryEquip(Mint(items, _cache, "Lamp"), new int2(2, 0))); + Assert.False(station.UnoccupiedSpace[new int2(2, 0)]); + Assert.True(station.UnoccupiedSpace[new int2(5, 5)]); + Assert.True(station.TryEquip(Mint(items, _cache, "Lamp"), new int2(5, 5))); + } + [Fact] public void AFullProductStopsItsOresBeingBought() { diff --git a/tests/Aetheria.Shared.Tests/StationWantsTests.cs b/tests/Aetheria.Shared.Tests/StationWantsTests.cs index 6810159b4..a0177faf6 100644 --- a/tests/Aetheria.Shared.Tests/StationWantsTests.cs +++ b/tests/Aetheria.Shared.Tests/StationWantsTests.cs @@ -85,6 +85,60 @@ public sealed partial class RunStartTests return StationOfKind(arena, kind); } + // A haul order from the refinery's orbit (a run record, as the demo's own order is), naming the goods. + private void OrderFrom(OrbitalEntity station, params CultRecordKey[] goods) => + _cache.Upsert(typeof(HaulOrderData), new HaulOrderData + { + From = new CultRecordRef(station.OrbitData), To = new CultRecordRef(station.OrbitData), + Goods = goods.Select(good => new CultRecordRef(good)).ToList() + }, HaulOrderData.KeyOf("refinery-onward")); + + // A good bought for an onward haul holds a share of the refinery's silo as a product does (cut facility-output-room): a sale of it stops at + // the share, the products' shares are not crowded, and the room of a product and of an ordered good is one rule. + [Fact] + public void AnOrderedGoodHoldsItsOwnShareOfTheSilo() + { + var (_, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var refinery = StationOfKind(arena, "processing"); + var steel = new CultRecordKey("commodity:steel"); + var iron = new CultRecordKey("commodity:iron"); + var before = StationWants.Allocation(refinery, iron); + OrderFrom(refinery, steel); + var slots = Production.RunList(_cache, _cache.RefOf(_cache.GetByName("Refinery")).Key).Select(r => r.Output.Key).Union(new[] { steel }).Count(); + var share = 64 / slots * _cache.Get(steel).MaxStack; + Assert.Equal(share, StationWants.Allocation(refinery, steel)); + Assert.Equal(StationWants.Allocation(refinery, steel), StationWants.Allocation(refinery, iron)); + Assert.True(StationWants.Allocation(refinery, iron) <= before); + + var hold = staged.Player.CargoBays[0]; + var credits = 0; + var sold = 0; + for (var stack = 0; stack < 8; stack++) + { + var offered = new SimpleCommodity { Data = new CultRecordRef(steel), Quantity = _cache.Get(steel).MaxStack }; + if (!hold.TryStore(offered)) break; + sold += StationServices.TrySellPart(hold, refinery, offered, ref credits).Sold; + } + Assert.Equal(share, sold); + Assert.Equal(0, StationWants.Room(refinery, steel)); + Assert.Equal(StationWants.Allocation(refinery, iron), StationWants.Room(refinery, iron)); + Assert.Equal(share, refinery.CargoBays.Where(bay => bay.Data is SiloData).Sum(bay => bay.Count(steel))); + } + + // A good both drawn and ordered lands in the stock bays and in the silo, each by its own rule. + [Fact] + public void ADrawnAndOrderedGoodLandsInBoth() + { + var refinery = DemoStation("processing"); + var ore = StationWants.Of(refinery).First(key => FieldKinds.IsOre(_cache, _cache.Get(new CultRecordRef(key)))); + Assert.DoesNotContain(refinery.CargoBays.Where(bay => bay.Data is SiloData), bay => StationWants.Bays(refinery, ore).Contains(bay)); + OrderFrom(refinery, ore); + var bays = StationWants.Bays(refinery, ore).ToArray(); + Assert.Contains(bays, bay => bay.Data is SiloData); + Assert.Contains(bays, bay => !(bay.Data is SiloData)); + } + // 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] diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 90592b2bc..db1b32919 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -71,7 +71,7 @@ public static class EconomyCommand { EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList, EconomyChecks.LWeights, EconomyChecks.LShape, EconomyChecks.LPrice }; // A batch is compiled code under tools/AetherDb/Economy/ and runs with the operator's authority: reviewed code, never an input. - private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [...]] [--cap ] | balance --drain [...] [--window ] [--horizon ]\nbalance reads the chain and changes nothing; --loop adds the player loop (a mining sortie per seed, default seeds 1 2 3 69 97, every belt of each, cap 150 sim seconds a sortie) and the offered gear ladders; --drain, not in the same call, adds a station block per seed: sorties to fill, the window (default 600 sim s) on screen and by spans, and the horizon (default 24 sim h) by spans. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made good (a commodity, or a design with a recipe) to the price its chain derives; with no batch it reprices alone."; + private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [...]] [--cap ] | balance --drain [...] [--window ] [--horizon ] [--supply]\nbalance reads the chain and changes nothing; --loop adds the player loop (a mining sortie per seed, default seeds 1 2 3 69 97, every belt of each, cap 150 sim seconds a sortie) and the offered gear ladders; --drain, not in the same call, adds a station block per seed: sorties to fill, the window (default 600 sim s) on screen and by spans, and the horizon (default 24 sim h) by spans; --supply tops the wanted ores up through the landing rule every 600 sim s of the horizon (a long --horizon, such as 300, shows a station whose products fill with no outflow: H-drain-saturated). A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made good (a commodity, or a design with a recipe) to the price its chain derives; with no batch it reprices alone."; public static int Run(string[] args, TextWriter output) { @@ -113,6 +113,7 @@ public static class EconomyCommand if (!capped) cap = EconomyLoop.DefaultCap; if (!windowed) window = EconomyDrain.DefaultWindowSeconds; if (!horizoned) horizon = EconomyDrain.DefaultHorizonHours; + var supplied = rest.Remove("--supply"); var loopAt = rest.IndexOf("--loop"); var drainAt = rest.IndexOf("--drain"); var seeds = new List(); @@ -124,7 +125,7 @@ public static class EconomyCommand seeds.Add(seed); } // One of the two stages a call, its seeds last; each option belongs to its own stage. - if ((flagAt >= 0 ? rest.Count - 1 - seeds.Count : rest.Count) != 0 || (loopAt >= 0 && drainAt >= 0) || (capped && loopAt < 0) || ((windowed || horizoned) && drainAt < 0)) + if ((flagAt >= 0 ? rest.Count - 1 - seeds.Count : rest.Count) != 0 || (loopAt >= 0 && drainAt >= 0) || (capped && loopAt < 0) || ((windowed || horizoned || supplied) && drainAt < 0)) { output.WriteLine(Usage); return 1; @@ -135,7 +136,7 @@ public static class EconomyCommand loop = EconomyLoop.Report(db.Cache, settings, seedList.SelectMany(seed => EconomyLoop.Sorties(db.Root, seed, (float) cap)).ToList()); List drain = null; if (drainAt >= 0) - drain = seedList.Select(seed => EconomyDrain.Run(db.Root, seed, window, horizon, EconomyLoop.Sorties(db.Root, seed, EconomyLoop.DefaultCap))).ToList(); + drain = seedList.Select(seed => EconomyDrain.Run(db.Root, seed, window, horizon, EconomyLoop.Sorties(db.Root, seed, EconomyLoop.DefaultCap), supplied: supplied)).ToList(); return Balance(db.Cache, settings.EconomyWageSpread, output, loop, drain); } if (args.Length > 0 && args[0] == "author") diff --git a/tools/AetherDb/EconomyDrain.cs b/tools/AetherDb/EconomyDrain.cs index 1b72c33f9..6f42d2dcc 100644 --- a/tools/AetherDb/EconomyDrain.cs +++ b/tools/AetherDb/EconomyDrain.cs @@ -44,6 +44,8 @@ public sealed class FacilityDrain public Stall HorizonEnd; // The ores some recipe of this facility draws that the station still holds when the horizon ends. public List OresLeft = new List(); + // The products of this facility that stand at their share of the silo when the horizon ends: no cycle of theirs can start. + public List Saturated = new List(); } public sealed class OreDrain @@ -74,6 +76,9 @@ public sealed class StationDrain public List Outputs = new List(); // Sim seconds into the horizon at the end of the first span any facility ended stalled Room, or null. public double? FirstRoomStall; + // With the supply on: sim seconds into the horizon when a product first stood at its share, and the count of wanted ores at the start and end. + public double? FirstSaturated; + public int WantedStart, WantedEnd; // Where the window by steps and by spans part: units held of a design, a facility's run progress, the sim time of its first Room stall. public List WindowDisagreements = new List(); } @@ -87,15 +92,19 @@ public sealed class DrainSample // Haulers taken out of the arena before anything else: the harness measures facilities, so no haul moves on screen or in the spans. public int Parked; public double WindowSeconds, HorizonHours; + // The wanted ores were topped up through the landing rule every SupplySpan of the horizon. + public bool Supplied; public List Stations = new List(); } public static class EconomyDrain { - public const string HStall = "H-drain-stall", HSim = "H-drain-sim", HSortie = "H-drain-sortie"; + public const string HStall = "H-drain-stall", HSim = "H-drain-sim", HSortie = "H-drain-sortie", HSaturated = "H-drain-saturated"; public const double DefaultWindowSeconds = 1200, DefaultHorizonHours = 24; // One span of the off-screen path, in sim seconds: the resolution of every time the horizon reports. public const double Span = 60; + // How often the supplied horizon brings the wanted ores again, in sim seconds (a multiple of Span): the resolution of the first-saturated time. + private const double SupplySpan = 600; private const int MaxSorties = 500; // Stepped and spanned run progress differ by float rounding only; a skew of one step (0.02 s) is far outside this. A cycle that ends on a // span boundary is met by the steps one or two steps later, as their sum falls just short of it. @@ -106,7 +115,7 @@ public static class EconomyDrain // Report and is not a sortie of the fill count. beforeWindow sees the arena after the fill and before the window is read by steps // or by spans (a test makes room or switches a facility off there); onStep sees it before each on-screen step (a test skews time). public static DrainSample Run(string root, uint seed, double windowSeconds, double horizonHours, IReadOnlyList sorties, - Action beforeWindow = null, Action onStep = null) + Action beforeWindow = null, Action onStep = null, bool supplied = false) { if (!double.IsFinite(windowSeconds) || windowSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(windowSeconds), "the window must be a positive, finite number of sim seconds"); if (!double.IsFinite(horizonHours) || horizonHours <= 0) throw new ArgumentOutOfRangeException(nameof(horizonHours), "the horizon must be a positive, finite number of sim hours"); @@ -118,7 +127,7 @@ public static class EconomyDrain foreach (var hauler in haulers) if (demo.Arena.Remove(hauler)) hauler.Deactivate(); var usable = sorties.Where(s => s.Measured && s.Mined.Count > 0).ToList(); - var sample = new DrainSample { Seed = seed, Parked = haulers.Count, Usable = usable.Count, Excluded = sorties.Except(usable).ToList(), WindowSeconds = windowSeconds, HorizonHours = horizonHours }; + var sample = new DrainSample { Seed = seed, Parked = haulers.Count, Usable = usable.Count, Excluded = sorties.Except(usable).ToList(), WindowSeconds = windowSeconds, HorizonHours = horizonHours, Supplied = supplied }; var stations = new[] { ("processing", demo.Processing), ("trade-hub", demo.Zenith) }; var runs = new List(); foreach (var (role, station) in stations) @@ -191,7 +200,7 @@ public static class EconomyDrain } // The horizon by spans on a copy of the filled station, sampled each sim hour. - foreach (var run in runs) run.Horizon(horizonHours); + foreach (var run in runs) run.Horizon(horizonHours, supplied); return sample; } @@ -207,7 +216,9 @@ public static class EconomyDrain foreach (var station in sample.Stations) { var where = $"seed {sample.Seed} {station.Role}"; - foreach (var facility in station.Facilities.Where(f => f.OresLeft.Count > 0 && (f.HorizonEnd == Stall.Room || f.HorizonEnd == Stall.Inputs))) + foreach (var facility in station.Facilities.Where(f => sample.Supplied && f.Saturated.Count > 0 && f.HorizonEnd == Stall.Room)) + faults.Add(new EconomyFault(HSaturated, where, $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled Room with {string.Join(", ", facility.Saturated)} at their share of the silo (first at {(station.FirstSaturated ?? 0) / 3600:0.##} h) and nothing taking them out: the station buys {station.WantedEnd} of the {station.WantedStart} goods it wanted and cannot use the ore it holds. Outflow is follow-up demo-fabricator-region and region-haul-legs.")); + foreach (var facility in station.Facilities.Where(f => !(sample.Supplied && f.Saturated.Count > 0 && f.HorizonEnd == Stall.Room) && f.OresLeft.Count > 0 && (f.HorizonEnd == Stall.Room || f.HorizonEnd == Stall.Inputs))) faults.Add(new EconomyFault(HStall, where, $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled {facility.HorizonEnd} with {string.Join(", ", facility.OresLeft)} still held: the station does not drain what it took.")); if (station.WindowDisagreements.Count > 0) faults.Add(new EconomyFault(HSim, where, $"the {sample.WindowSeconds:0.##} s window by steps and by spans disagree: {string.Join("; ", station.WindowDisagreements)}.")); @@ -219,7 +230,7 @@ public static class EconomyDrain public static void Print(DrainSample sample, TextWriter output) { var inv = CultureInfo.InvariantCulture; - output.WriteLine(string.Format(inv, "\nStation drain, seed {0} (window {1:0.##} s on screen and by spans; horizon {2:0.##} h by spans of {3:0} s)", sample.Seed, sample.WindowSeconds, sample.HorizonHours, Span)); + output.WriteLine(string.Format(inv, "\nStation drain, seed {0} (window {1:0.##} s on screen and by spans; horizon {2:0.##} h by spans of {3:0} s{4})", sample.Seed, sample.WindowSeconds, sample.HorizonHours, Span, sample.Supplied ? ", wanted ores topped up every 600 s" : "")); output.WriteLine($" haulers parked: {sample.Parked} (no haul moves on screen or in the spans: this block measures facilities; haul throughput is follow-up drain-haul-throughput, off-screen hauling region-haul-legs)"); output.WriteLine(" window compares units held, run progress and first-Room time; a Room-stalled facility holds at its cycle whatever the time, so a skew there shows only as first-Room time within one span"); output.WriteLine(" window compares units held, run progress and first-Room time; a Room-stalled facility holds at its cycle whatever the time, so a skew there shows only as first-Room time within one span"); output.WriteLine($" sorties usable {sample.Usable} of {sample.Usable + sample.Excluded.Count}" + string.Concat(sample.Excluded.Select(x => $"; excluded belt {x.Belt + 1}/{x.Belts} {x.BeltKind} {x.Outcome} at {x.SimSeconds:0.#} s"))); @@ -252,6 +263,11 @@ public static class EconomyDrain output.WriteLine($" output {pile.Metal}: units held per hour {string.Join(" ", pile.Hourly)}"); var empty = station.Outputs.Where(p => p.Hourly.All(units => units == 0)).Select(p => p.Metal).ToList(); if (empty.Count > 0) output.WriteLine($" outputs held at 0 all horizon: {string.Join(", ", empty)}"); + if (sample.Supplied && station.Outputs.Count > 0) + output.WriteLine(station.FirstSaturated.HasValue + ? string.Format(inv, " supplied: first product at its share at {0:0} sim s ({1:0.##} h); wanted goods {2} -> {3}; at the horizon saturated: {4}", station.FirstSaturated.Value, station.FirstSaturated.Value / 3600, station.WantedStart, station.WantedEnd, + string.Join(", ", station.Facilities.SelectMany(f => f.Saturated).Distinct())) + : string.Format(inv, " supplied: no product reached its share in the horizon; wanted goods {0} -> {1}", station.WantedStart, station.WantedEnd)); if (station.Outputs.Count > 0) output.WriteLine(station.FirstRoomStall.HasValue ? string.Format(inv, " first Room stall at {0:0} sim s ({1:0.##} h)", station.FirstRoomStall.Value, station.FirstRoomStall.Value / 3600) @@ -404,13 +420,16 @@ public static class EconomyDrain return last; } - public void Horizon(double hours) + public void Horizon(double hours, bool supplied = false) { var catalog = Demo.Cache; var hold = new EntityHold(HorizonCopy); var facilities = Facilities(HorizonCopy).Select(f => f.unit).ToArray(); var outputs = facilities.SelectMany(unit => Production.RunList(catalog, unit.EquippableItem.Data.Key)).Select(r => r.Output.Key).Distinct().OrderBy(k => k.Value, StringComparer.Ordinal).ToList(); - var oreKeys = Ores.Where(ore => hold.Held(ore) > 0).ToList(); + var oreKeys = Ores.Where(ore => supplied || hold.Held(ore) > 0).ToList(); + Drain.WantedStart = StationWants.Of(HorizonCopy).Count; + var recipes = facilities.SelectMany(unit => Production.RunList(catalog, unit.EquippableItem.Data.Key)).GroupBy(r => r.Output.Key).Select(g => g.First()).ToList(); + List Full() => recipes.Where(recipe => StationWants.Room(HorizonCopy, recipe.Output.Key) < recipe.OutputCount).ToList(); foreach (var ore in oreKeys) Drain.Ores.Add(new OreDrain { Ore = Name(catalog, ore.Value) }); foreach (var metal in outputs) Drain.Outputs.Add(new OutputPile { Metal = Name(catalog, metal.Value) }); void Sample() @@ -418,20 +437,45 @@ public static class EconomyDrain for (var i = 0; i < oreKeys.Count; i++) Drain.Ores[i].Hourly.Add(hold.Held(oreKeys[i])); for (var i = 0; i < outputs.Count; i++) Drain.Outputs[i].Hourly.Add(hold.Held(outputs[i])); } + // The shipped sale's landing, as a seller bringing the ore again every span: each ore into the bays that may hold it, to their room. + void TopUp() + { + foreach (var ore in Ores) + { + var maxStack = catalog.Get(ore).MaxStack; + foreach (var (bays, room) in StationWants.Landing(HorizonCopy, ore).ToArray()) + { + var left = room; + for (var quantity = maxStack; quantity >= 1; quantity /= 2) + while (left >= quantity && bays.Any(bay => bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(ore), Quantity = quantity }))) left -= quantity; + } + } + } + if (supplied) TopUp(); Sample(); var nextHour = 3600.0; + var nextSupply = SupplySpan; var ends = Spans(HorizonCopy, hours * 3600, (at, stalls) => { if (!Drain.FirstRoomStall.HasValue && stalls.Any(stall => stall == Stall.Room)) Drain.FirstRoomStall = at; + if (supplied && at >= nextSupply - 1e-9) + { + if (!Drain.FirstSaturated.HasValue && Full().Count > 0) Drain.FirstSaturated = at; + TopUp(); + nextSupply += SupplySpan; + } for (var i = 0; i < oreKeys.Count; i++) if (!Drain.Ores[i].EmptyAt.HasValue && hold.Held(oreKeys[i]) == 0) Drain.Ores[i].EmptyAt = at; if (at >= nextHour - 1e-9) { Sample(); nextHour += 3600; } }); + Drain.WantedEnd = StationWants.Of(HorizonCopy).Count; + var saturated = Full().Select(recipe => Name(catalog, recipe.Output.Key.Value)).ToList(); HashSet Draws(EquippedItem unit) => Production.RunList(catalog, unit.EquippableItem.Data.Key).SelectMany(recipe => Production.Draws(catalog, recipe)).ToHashSet(); for (var i = 0; i < ends.Length; i++) { var draws = Draws(facilities[i]); Drain.Facilities[i].HorizonEnd = ends[i]; + Drain.Facilities[i].Saturated = saturated; Drain.Facilities[i].OresLeft = oreKeys.Where(ore => draws.Contains(ore) && hold.Held(ore) > 0).Select(ore => Name(catalog, ore.Value)).ToList(); } for (var i = 0; i < oreKeys.Count; i++)