From 1ce71101ffb38b903e8c638e9d7a1537db9c0626 Mon Sep 17 00:00:00 2001 From: soul Date: Sun, 29 Nov 2026 08:56:53 +0100 Subject: [PATCH] Facility: the rig asks the deposit pick which ore to work, lands where Advance lands, and a mixed list splits Soul s1 on cut-facility-extraction. - shares-follow-first-belt, rig-hammers-first-rocks: on screen a rig works an ore at a time as Production.Pick names it from the cycles it has worked (the one owner of which ore next, Advance's too), at that recipe's own count and cycle, on a whole rock whose belt holds the ore, chosen by a stable hash of the cycle so rocks take turns. FireControl.Extract takes optional `only` (the one ore a rock pays) and `landing` (the bays); the player passes neither. Production.OreRate is deleted: nothing reads a mean rate now. - rig-ignores-silo-share: the units land in StationWants.OutputBays, and nothing is worn unless StationWants.Room and a free cell say the ore lands, as Advance's put does. - mixed-raw-list-picks-on-screen: on screen the ore entries of a design work the rocks and every other entry runs Advance alone. - run-writer-comment-stale: ItemInstance.Run names its writer. ExtractionTests: two belts of two ores agree on shares (0.71-1.41), rocks wear together (4 of 20 where a first-rock rig holds one), the silo's share stops a rig and the station's other bay stays empty, a mixed list splits. Co-Authored-By: Claude Sonnet 5.5 --- .../ServerShared/Behaviors/Facility.cs | 107 +++++++++++------ Assets/Scripts/ServerShared/Deposits.cs | 2 +- Assets/Scripts/ServerShared/FireControl.cs | 8 +- Assets/Scripts/ServerShared/ItemInstance.cs | 2 +- Assets/Scripts/ServerShared/Production.cs | 30 ++--- .../Aetheria.Shared.Tests/ExtractionTests.cs | 111 +++++++++++------- 6 files changed, 157 insertions(+), 103 deletions(-) diff --git a/Assets/Scripts/ServerShared/Behaviors/Facility.cs b/Assets/Scripts/ServerShared/Behaviors/Facility.cs index 4c4ebc8e7..8d0ff459a 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Facility.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Facility.cs @@ -26,14 +26,16 @@ public class FacilityData : BehaviorData // the run list of its design, fixed for a run because the catalog is. // // Two paths, by where the zone is (ruling auto-mining-is-off-screen-only). Off screen every facility advances by Production.Advance: -// an ore rig's raw recipes start by the deposit pick. On screen a run list of nothing but raw ore works the zone's rocks instead (Work), -// through Zone.Wear and FireControl.Extract, the player's own mining, at Production.OreRate, the rate Advance's pick averages to; the -// player sees the rocks break, and the unit's FacilityRun is left as the off-screen path last wrote it. Any other list, a skimmer's -// included (ruling skimmers-run-their-recipe-on-screen-for-now), runs Advance in both. +// an ore rig's raw recipes start by Production.Pick. On screen the raw ore entries of the list work the zone's rocks instead (Work), +// through Zone.Wear and FireControl.Extract, the player's own mining, an ore at a time as Production.Pick names it, at the recipe's own +// cycle and count, so the units of each ore come as the pick has them off screen; the player sees the rocks break, and the unit's +// FacilityRun is left as the off-screen path last wrote it. Every other entry, a skimmer's volatiles included (ruling +// skimmers-run-their-recipe-on-screen-for-now), runs Advance in both. public class Facility : Behavior { private IReadOnlyList _runList; - private bool _mines; + private IReadOnlyList _ores; + private IReadOnlyList _others; private EntityHold _hold; // Why the facility advanced no further this step: derived by Advance every step, never stored on the unit. @@ -46,66 +48,101 @@ public class Facility : Behavior // How many steps tried to take a cycle's inputs: a diagnostic of the skip above, derived and not persisted. public int Attempts { get; private set; } + // The rig's on-screen cycle, derived and not persisted: how many it has worked (the pick's count, begun from the unit's own count + // when first worked), the recipe and rock of the one under way, and the sim seconds into it. + private long _worked = -1; + private RecipeData _working; + private ChunkId _rock; + private bool _rocked; + private double _into; + public Facility(FacilityData data, EquippedItem item) : base(data, item) { SetRunList(); } - // The run list as the catalog holds it, and whether it is all raw ore: the lists that work rocks on screen. + // The run list as the catalog holds it, split into the raw ore entries that work rocks on screen and the rest. private void SetRunList() { - _runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key); - _mines = _runList.Count > 0 && _runList.All(recipe => Recipes.IsRaw(ItemManager.ItemData, recipe) - && ItemManager.ItemData.Get(recipe.Output) is SimpleCommodityData output && FieldKinds.IsOre(ItemManager.ItemData, output)); + var catalog = ItemManager.ItemData; + _runList = Production.RunList(catalog, Item.EquippableItem.Data.Key); + bool Ore(RecipeData recipe) => Recipes.IsRaw(catalog, recipe) && catalog.Get(recipe.Output) is SimpleCommodityData output && FieldKinds.IsOre(catalog, output); + _ores = _runList.Where(Ore).ToArray(); + _others = _runList.Where(recipe => !Ore(recipe)).ToArray(); } // The on-screen step: one zone step. public override bool Execute(float dt) { - if (_mines) Work(dt); - else Advance(dt); + if (_ores.Count > 0) Work(dt); + if (_others.Count > 0 || _ores.Count == 0) Advance(dt, _others); return true; } // The off-screen step: the span the zone missed, always the recipe rule. - public void Span(double seconds) => Advance(seconds); + public void Span(double seconds) => Advance(seconds, _runList); - // The rock an ore rig works, in sim time dt: the first whole rock in belt Site then index order (the order Deposits reads the - // belts in) takes the damage that owes OreRate x dt units (what FireControl.Extract pays for the damage it absorbs), and Extract pays - // the station by dice of its own stream. Barren with no whole rock or no ore the ground holds; Room, with nothing worn, when no bay - // has a cell for any of its ores. A cycle begun off screen resumes when the zone is off screen again. + // Whether the station's output bays have a cell for one unit of the good and its share of the silo has room: the landing Advance's + // put takes, asked before any rock is worn. + private bool Lands(CultRecordKey good) => + StationWants.Room(Entity, good) >= 1 && StationWants.OutputBays(Entity, good).Any(bay => + bay.TryFindSpace(new SimpleCommodity { Data = new CultRecordRef(good), Quantity = 1 })); + + // The rock an ore rig works, in sim time dt. A cycle begins at Production.Pick on the cycles worked (then the next recipe the ground + // holds and the station has room for, as Advance goes on), picks a whole rock whose belt holds that ore, by a stable hash of the cycle + // (so rocks take turns), and for the recipe's Cycle seconds wears it by what OutputCount units of it owe (what FireControl.Extract + // pays for the damage it absorbs); a rock that breaks gives way to the next. Extract pays that ore only, into the output bays, by dice + // of its own stream. Barren with no ore the ground holds or no whole rock of it; Room, with nothing worn, when the ore has no landing. private void Work(double dt) { _hold ??= new EntityHold(Entity); var catalog = ItemManager.ItemData; var zone = Entity.Zone; - var rate = Production.OreRate(catalog, _runList, _hold); - if (zone == null || !(rate > 0)) { Stall = Stall.Barren; return; } - - var rock = default(ChunkId); - var found = false; - foreach (var belt in zone.AsteroidBelts.OrderBy(entry => entry.Value.Data.SiteOr(entry.Key), StringComparer.Ordinal)) + if (zone == null) { Stall = Stall.Barren; return; } + if (_worked < 0) _worked = Item.EquippableItem.Run?.Cycles ?? 0; + if (_working == null) { - for (var index = 0; index < belt.Value.Data.Asteroids.Length && !found; index++) - if (zone.ChunkExists(rock = new ChunkId(belt.Key, index))) found = true; - if (found) break; + var pick = Production.Pick(_ores, _worked, _hold); + if (pick < 0) { Stall = Stall.Barren; return; } + for (var step = 0; step < _ores.Count && _working == null; step++) + { + var candidate = _ores[(pick + step) % _ores.Count]; + if (_hold.Deposit(candidate.Output.Key) > 0f && Lands(candidate.Output.Key)) _working = candidate; + } + if (_working == null) { Stall = Stall.Room; return; } + _into = 0; + _rocked = false; + } + var ore = _working.Output.Key; + if (!Lands(ore)) { Stall = Stall.Room; return; } + if (!_rocked || !zone.ChunkExists(_rock)) + { + var province = zone.GalaxyZone?.Province?.Type ?? default; + var whole = new List(); + foreach (var belt in zone.AsteroidBelts.OrderBy(entry => entry.Value.Data.SiteOr(entry.Key), StringComparer.Ordinal)) + { + if (!FieldKinds.Yield(belt.Value.Data.Kind, province, catalog).Any(yield => yield.Commodity.Key.Equals(ore))) continue; + for (var index = 0; index < belt.Value.Data.Asteroids.Length; index++) + if (zone.ChunkExists(new ChunkId(belt.Key, index))) whole.Add(new ChunkId(belt.Key, index)); + } + if (whole.Count == 0) { _rocked = false; Stall = Stall.Barren; return; } + _rock = whole[(int) ($"rock:{_worked}:{ore.Value}".StableHash() % (uint) whole.Count)]; + _rocked = true; } - if (!found) { Stall = Stall.Barren; return; } - - var room = _runList.Any(recipe => _hold.Deposit(recipe.Output.Key) > 0f && Entity.CargoBays.Any(bay => - bay.TryFindSpace(new SimpleCommodity { Data = new CultRecordRef(recipe.Output.Key), Quantity = 1 }))); - if (!room) { Stall = Stall.Room; return; } var settings = zone.Settings; - var size = ((AsteroidBeltData) zone.Planets[rock.Field]).Asteroids[rock.Index].Size; - var damage = (float) (rate * dt / settings.AsteroidYield.Evaluate(size) * settings.AsteroidHitpoints.Evaluate(size)); + var size = ((AsteroidBeltData) zone.Planets[_rock.Field]).Asteroids[_rock.Index].Size; + var damage = (float) (_working.OutputCount / (double) _working.Cycle * dt / settings.AsteroidYield.Evaluate(size) * settings.AsteroidHitpoints.Evaluate(size)); var place = Entity.Equipment.IndexOf(Item); var ordinal = SimulationDice.Mix(unchecked((uint) (long) Math.Floor(zone.ExactTime * 1000))) ^ (uint) place; - FireControl.Extract(zone, rock, zone.Wear(rock, damage), Entity, SimulationDice.For(zone.DropSeed, SimulationDice.RigStream, ordinal)); + FireControl.Extract(zone, _rock, zone.Wear(_rock, damage), Entity, SimulationDice.For(zone.DropSeed, SimulationDice.RigStream, ordinal), + ore, StationWants.OutputBays(Entity, ore)); Stall = Stall.None; + _into += dt; + if (_into >= _working.Cycle) { _worked++; _working = null; _rocked = false; } } - private void Advance(double seconds) + private void Advance(double seconds, IReadOnlyList list) { _hold ??= new EntityHold(Entity); var idle = Item.EquippableItem.Run == null || Item.EquippableItem.Run.Progress <= 0; @@ -115,7 +152,7 @@ public class Facility : Behavior // stale, so it is rebuilt from the catalog before that step. if (!idle && Production.Live(ItemManager.ItemData, Item.EquippableItem.Run.Recipe) == null) SetRunList(); - var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, seconds, _hold); + var (run, stall) = Production.Advance(ItemManager.ItemData, list, Item.EquippableItem.Run, seconds, _hold); Item.EquippableItem.Run = run; Stall = stall; if (idle && stall == Stall.Inputs) _failedAt = _hold.Revision; diff --git a/Assets/Scripts/ServerShared/Deposits.cs b/Assets/Scripts/ServerShared/Deposits.cs index 1bb4cca9e..d3d67114c 100644 --- a/Assets/Scripts/ServerShared/Deposits.cs +++ b/Assets/Scripts/ServerShared/Deposits.cs @@ -21,7 +21,7 @@ public class AtmosphereData // The one owner of what a zone's ground holds (ruling auto-mining-is-off-screen-only): the goods an ore rig mines or a skimmer // skims, in units, derived from the zone's bodies and never stored. Production.Advance picks its raw recipes by it off screen, -// and Production.OreRate reads it for the rate on screen. +// and an ore rig on screen works the rocks of the ore Production.Pick names from it. public static class Deposits { // The atmosphere every gas giant draws on, until a giant authors its own. diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 06448cc95..80ca9df2b 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -1830,14 +1830,18 @@ public static class FireControl // and never stored. A shot with no Source (a mine) yields nothing. The units go to the shooter's cargo bays in // stacks; what does not fit, or everything when the shooter has left the zone, floats at the rock (ruling // mining-overflow-floats). + // `only` restricts the rock to paying one ore (a rig working the rocks of the ore its pick named: Facility.Work), and `landing` is + // the bays the units go to instead of all of the shooter's (the station's output bays); the player's mining passes neither. // Draw order: the Bernoulli, then one draw per unit. - public static void Extract(Zone zone, ChunkId chunk, float absorbed, Entity shooter, Random dice) + public static void Extract(Zone zone, ChunkId chunk, float absorbed, Entity shooter, Random dice, CultRecordKey? only = null, + IEnumerable landing = null) { if (shooter == null || !(absorbed > 0f)) return; var settings = zone.Settings; var belt = zone.AsteroidBelts[chunk.Field]; var catalog = shooter.ItemManager.ItemData; var ores = FieldKinds.Yield(belt.Data.Kind, zone.GalaxyZone?.Province?.Type ?? default, catalog); + if (only != null) ores = ores.Where(ore => ore.Commodity.Key.Equals(only.Value)).ToArray(); if (ores.Length == 0) return; var size = belt.Data.Asteroids[chunk.Index].Size; @@ -1876,7 +1880,7 @@ public static class FireControl var stack = new SimpleCommodity { Data = new CultRecordRef(key), Quantity = Math.Min(left, maxStack) }; // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. var stored = false; - if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; + if (present) foreach (var bay in landing ?? shooter.CargoBays) if (stored = bay.TryStore(stack)) break; if (!stored) { adrift += stack.Quantity; diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index 513568ece..fc7bd85b5 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -98,7 +98,7 @@ public class EquippableItem : CraftedItemInstance [JsonProperty("powerTier"), Key(12)] public int PowerTier = PowerTiers.Unassigned; // A facility's cycle in progress: per-unit installation state like PowerTier, null on everything but a facility that has started - // a cycle. Its one writer is Facility.Execute, storing Production.Advance's result. 13 is CompoundCommodity's, so 14. + // a cycle. Its one writer is Facility, storing Production.Advance's result (off screen by span, on screen for a list that is not ore). 13 is CompoundCommodity's, so 14. [JsonProperty("run"), Key(14)] public FacilityRun Run; // The population a habitation unit houses: per-unit installation state like Run, null on everything but a habitation unit that has diff --git a/Assets/Scripts/ServerShared/Production.cs b/Assets/Scripts/ServerShared/Production.cs index 8164e5a15..6d5432f44 100644 --- a/Assets/Scripts/ServerShared/Production.cs +++ b/Assets/Scripts/ServerShared/Production.cs @@ -98,23 +98,11 @@ public static class Production return need; } - // The units per sim second of the list's ore recipes the ground holds: the expected output of Advance's deposit pick, so the one - // rate an ore rig runs at off screen and works the rocks at on screen. Each recipe i weighs D_i = hold.Deposit(output_i); it is - // picked in proportion to D_i / OutputCount_i and makes OutputCount_i units in Cycle_i seconds, so the rate is - // sum D_i / sum (D_i x Cycle_i / OutputCount_i). 0 when the list holds no ore the ground has. - public static double OreRate(CultCache catalog, IReadOnlyList runList, IProductionHold hold) - { - double deposit = 0, seconds = 0; - foreach (var recipe in runList) - { - if (!(catalog.Get(recipe.Output) is SimpleCommodityData output) || !FieldKinds.IsOre(catalog, output)) continue; - var held = hold.Deposit(recipe.Output.Key); - if (!(held > 0f)) continue; - deposit += held; - seconds += held * recipe.Cycle / Math.Max(1, recipe.OutputCount); - } - return seconds > 0 ? deposit / seconds : 0; - } + // Which raw recipe a facility works next, the one owner of that choice on screen and off: an index into runList by a stable pick + // on the cycles started so far, each recipe weighing its good's deposit per unit made (so the units of each held good come in + // proportion to its deposit); -1 when the ground holds none. Advance starts from it, and an ore rig on screen works the rocks of it. + public static int Pick(IReadOnlyList runList, long cycles, IProductionHold hold) => + FieldKinds.Pick($"extract:{cycles}", runList.Select(recipe => (double) hold.Deposit(recipe.Output.Key) / Math.Max(1, recipe.OutputCount)).ToArray()); // The facility's state after `seconds` of sim time, and why it is not advancing. An idle facility (run null or Progress 0) // starts the first recipe after the cursor, wrapping, whose units the hold grants and whose output the hold has room for @@ -124,8 +112,7 @@ public static class Production // same call, so a long span runs several cycles (the rule that makes one span equal as many steps as it covers); time that no cycle // can start is dropped. A facility with nothing to start writes nothing. // A raw recipe takes from the ground: it starts only where the hold's Deposit of its good is positive. A list of raw recipes starts - // at a pick (FieldKinds.Pick on the cycles started so far) weighted by each good's deposit per unit made, so the units of each held - // raw good come in proportion to its deposit, and a list whose ground holds none reads Barren and writes nothing. + // at Pick, and a list whose ground holds none reads Barren and writes nothing. public static (FacilityRun run, Stall stall) Advance(CultCache catalog, IReadOnlyList runList, FacilityRun run, double seconds, IProductionHold hold) { @@ -145,9 +132,8 @@ public static class Production var cursor = run == null ? -1 : IndexOf(runList, run.Recipe.Key); if (raw) { - // The cursor sits one before the pick, so the pick is the first candidate: units of each held good come in - // proportion to its deposit (a cycle makes OutputCount units, hence the weight per unit made). - var pick = FieldKinds.Pick($"extract:{cycles}", runList.Select(recipe => (double) hold.Deposit(recipe.Output.Key) / Math.Max(1, recipe.OutputCount)).ToArray()); + // The cursor sits one before the pick, so the pick is the first candidate. + var pick = Pick(runList, cycles, hold); if (pick < 0) return (run, Stall.Barren); cursor = pick - 1; } diff --git a/tests/Aetheria.Shared.Tests/ExtractionTests.cs b/tests/Aetheria.Shared.Tests/ExtractionTests.cs index 27b9263ad..c4e831160 100644 --- a/tests/Aetheria.Shared.Tests/ExtractionTests.cs +++ b/tests/Aetheria.Shared.Tests/ExtractionTests.cs @@ -80,7 +80,11 @@ public sealed class ExtractionTests : IDisposable _cache.Upsert(new HullData { Name = "Test Yard", HullType = HullType.Station, Shape = Solid(8, 8), Price = 1, Durability = 10, Mass = 1000, - Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = Solid(2, 2), Transform = "Fa.1" } } + 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" } + } }); _cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Price = 20, Durability = 4 }); _cache.Upsert(new CargoBayData { Name = "Vault", Shape = new Shape(), InteriorShape = Solid(12, 12), Price = 20, Durability = 4 }); @@ -156,28 +160,6 @@ public sealed class ExtractionTests : IDisposable private const double PerUnitBound = 2.28; - // OreRate is what the pick averages to, whatever the counts and cycles: units made over 40000 s against it. Shipped reading about 1; - // without the division by OutputCount in OreRate it would claim half the rate (2.0 the other way), so the bound is 1.41. - [Fact] - public void OreRateIsWhatAdvanceAverages() - { - var a = Raw("Fix Rate A", 1, 10); - var b = Raw("Fix Rate B", 8, 40); - var kind = new FieldKindData { Name = "Fix Rate Field", CrossSection = 1f, GenerationWeight = 0f }; - kind.Yields.Add(new FieldYield { Commodity = new CultRecordRef(a.Output.Key), Abundance = 1f }); - kind.Yields.Add(new FieldYield { Commodity = new CultRecordRef(b.Output.Key), Abundance = 1f }); - _cache.Upsert(kind); - var ground = new Ground { Deposits = { [a.Output.Key] = 3f, [b.Output.Key] = 1f } }; - var rate = Production.OreRate(_cache, new[] { a, b }, ground); - Assert.Equal(4.0 / (3 * 10 / 1.0 + 1 * 40 / 8.0), rate, 6); - Production.Advance(_cache, new[] { a, b }, null, 40000, ground); - var made = ground.Held(a.Output.Key) + ground.Held(b.Output.Key); - Assert.InRange(made / 40000.0 / rate, 1 / OreRateBound, OreRateBound); - Assert.Equal(0.0, Production.OreRate(_cache, new[] { a, b }, new Ground())); - } - - private const double OreRateBound = 1.41; - [Fact] public void UnheldGoodNeverStarts() { @@ -253,7 +235,7 @@ public sealed class ExtractionTests : IDisposable // A zone of a sun, one belt of each count of rocks (kind `fields[i]`), `giants` gas giants, and a Test Yard station holding the // named facility and bay. - private World Build(string facility, int[] beltRocks, FieldKindData[] fields = null, int giants = 0, string bay = "Vault") + private World Build(string facility, int[] beltRocks, FieldKindData[] fields = null, int giants = 0, string bay = "Vault", bool silo = false) { var items = new ItemManager(1u, _cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); var sunOrbit = _cache.Upsert(new OrbitData { FixedPosition = float2.zero }).Key; @@ -289,6 +271,7 @@ public sealed class ExtractionTests : IDisposable var station = new OrbitalEntity(items, zone, Mint(items, "Test Yard"), default, new EntitySettings()); Assert.True(station.TryEquip(Mint(items, facility), new int2(0, 0))); Assert.True(station.TryEquip(Mint(items, bay), new int2(4, 4))); + if (silo) Assert.True(station.TryEquip(Mint(items, "Silo"), new int2(2, 0))); zone.Admit(station, piloted: false); var unit = station.Equipment.First(equipped => equipped.Behaviors.Any(behavior => behavior is Facility)); world.Items = items; @@ -312,30 +295,36 @@ public sealed class ExtractionTests : IDisposable private int Units(World world) => world.Hold.Held(_oreA) + world.Hold.Held(_oreB); + // The rig works the rocks, rocks taking turns: over 120 s of cycles of 2 s, rocks of the belt are worn at the same time (a rig that + // hammered the first whole rock would hold one worn rock at a time), the units land in the bays, and the unit's FacilityRun is untouched. [Fact] public void OnScreenRigWearsRocks() { - var world = Build("Extraction Rig", new[] { 3 }); - var first = new ChunkId(world.Belts[0], 0); - var second = new ChunkId(world.Belts[0], 1); - var yield = world.Zone.Settings.AsteroidYield.Evaluate(.5f); - var steps = 0; - while (world.Zone.ChunkExists(first) && steps++ < 60000) world.Zone.Update(SimClock.GameStep); - Assert.False(world.Zone.ChunkExists(first), "the first whole rock in index order broke"); - Assert.True(world.Zone.ChunkExists(second)); - Assert.Equal(world.Zone.AsteroidBelts[world.Belts[0]].UndamagedSize(1, world.Zone.Settings), world.Zone.ChunkRadius(second)); + var world = Build("Extraction Rig", new[] { 20 }); + var belt = world.Zone.AsteroidBelts[world.Belts[0]]; + var rocks = Enumerable.Range(0, 20).Select(index => new ChunkId(world.Belts[0], index)).ToArray(); + var worn = 0; + for (var second = 0; second < 120; second++) + { + Step(world, 1); + worn = Math.Max(worn, rocks.Count(rock => world.Zone.ChunkExists(rock) && world.Zone.ChunkRadius(rock) < belt.UndamagedSize(rock.Index, world.Zone.Settings))); + } + Assert.InRange(worn, WornLow, 20); Assert.Null(world.Unit.Run); Assert.Equal(Stall.None, world.Facility.Stall); - var units = Units(world); - Assert.InRange(units, 1, (int) Math.Ceiling(yield) + 2); - Assert.Equal(units, world.Hold.Held(_oreA) + world.Hold.Held(_oreB)); + Assert.InRange(Units(world), 30, 90); } + // At 120 s the units are 53 of the 60 owed at half a unit a second; rocks worn at once peaked at about 9 where a first-rock rig holds 1: the bound sits + // between by the margin rule, 3. + private const int WornLow = 4; + private (double totals, double shares, int on, int off) ReadAgreement() { const double seconds = 600; - var on = Build("Extraction Rig", new[] { 40 }); - var off = Build("Extraction Rig", new[] { 40 }); + // Two belts of different ores: A 3 to 1 with B, and B alone, so the ground holds A 15 rock-yields, B 25. + var on = Build("Extraction Rig", new[] { 20, 20 }, new[] { _field, _fieldB }); + var off = Build("Extraction Rig", new[] { 20, 20 }, new[] { _field, _fieldB }); Step(on, seconds); for (var at = 1; at <= seconds / RegionClock.Span; at++) off.Zone.AdvanceTo(at * RegionClock.Span); var shareOn = (double) on.Hold.Held(_oreA) / Units(on); @@ -352,10 +341,11 @@ public sealed class ExtractionTests : IDisposable Assert.InRange(shares, ShareLow, ShareHigh); } - // Shipped readings: total units on screen over off 0.953 (286 over 300; the Bernoulli of each step's owed fraction is a Poisson count, one - // sigma about 6%), and the on-screen share of the first ore over the off-screen one 1.064. Claimed mutants: the rate doubled (about 1.9) - // or halved (about 0.48) gives 1.35 and 0.68; ore drawn evenly instead of by the ground (share ratio about 0.67) gives 0.84. - private const double RateLow = 0.68, RateHigh = 1.35, ShareLow = 0.84, ShareHigh = 1.3; + // Shipped readings: total units on screen over off 0.953 at one belt (the Bernoulli of each step's owed fraction is a Poisson count, one + // sigma about 6%), and, in the zone of two belts, the first ore's share on screen over off. Claimed mutants: the rate doubled (about + // 1.9) or halved (about 0.48) gives 1.35 and 0.68; a rig that works the first belt only (A's share 0.75 where the ground holds 0.375, + // a ratio of 2) gives 1.41. + private const double RateLow = 0.68, RateHigh = 1.35, ShareLow = 0.71, ShareHigh = 1.41; [Fact] public void RigStopsWhenFull() @@ -376,6 +366,43 @@ public sealed class ExtractionTests : IDisposable Assert.Equal(2.0, off.Unit.Run.Progress); } + // Where a rig's ore lands is where Advance's put lands it: the silo, up to its share of each good, and never the station's other bays. + [Fact] + public void RigLandsInTheSilosShare() + { + var world = Build("Extraction Rig", new[] { 20 }, silo: true); + var silo = world.Station.CargoBays.Single(bay => bay.Data is SiloData); + var vault = world.Station.CargoBays.Single(bay => !(bay.Data is SiloData)); + var shareA = StationWants.Allocation(world.Station, _oreA).Value; + var shareB = StationWants.Allocation(world.Station, _oreB).Value; + Step(world, 3000); + Assert.Equal(0, vault.Count(_oreA) + vault.Count(_oreB)); + Assert.True(silo.Count(_oreA) > 0 && silo.Count(_oreB) > 0, $"silo holds {silo.Count(_oreA)} and {silo.Count(_oreB)}"); + Assert.InRange(silo.Count(_oreA), 0, shareA); + Assert.InRange(silo.Count(_oreB), 0, shareB); + // 3000 s at half a unit a second is 1500 units, far past the shares: the cycle of the ore whose share fills first holds its batch + // for room, as Advance's put does, and the rig stands there. + Assert.Equal(Stall.Room, world.Facility.Stall); + Assert.True(silo.Count(_oreA) == shareA || silo.Count(_oreB) == shareB, $"A {silo.Count(_oreA)} of {shareA}, B {silo.Count(_oreB)} of {shareB}"); + } + + // A design that lists ore and volatiles: on screen the ore goes by the rocks and the volatile by its recipe, never the ore by the pick. + [Fact] + public void MixedListSplitsOnScreen() + { + var methane = _cache.Get(RecipeData.KeyOf(Good("Methane"))); + methane.Facility = new CultRecordRef(Design("Extraction Rig")); + _cache.Upsert(typeof(RecipeData), methane, RecipeData.KeyOf(Good("Methane"))); + var world = Build("Extraction Rig", new[] { 20 }, giants: 1); + var belt = world.Zone.AsteroidBelts[world.Belts[0]]; + Step(world, 120); + Assert.True(world.Hold.Held(Good("Methane")) > 0, "the volatile runs its recipe"); + Assert.Equal(RecipeData.KeyOf(Good("Methane")), world.Unit.Run.Recipe.Key); + Assert.True(Units(world) > 0, "the ore comes by the rocks"); + Assert.Contains(Enumerable.Range(0, 20), index => !world.Zone.ChunkExists(new ChunkId(world.Belts[0], index)) + || world.Zone.ChunkRadius(new ChunkId(world.Belts[0], index)) < belt.UndamagedSize(index, world.Zone.Settings)); + } + // A skimmer runs its recipe in both paths, so a span of steps and a span of time read alike, byte for byte. [Fact] public void SkimmerSpansEqualSteps()