diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs index 296dcffe0..6b0f2ea80 100644 --- a/tools/AetherDb/EconomyLoop.cs +++ b/tools/AetherDb/EconomyLoop.cs @@ -98,7 +98,7 @@ public static class EconomyLoop // Every belt of every default seed is a sample (11 of them), so the cap is what bounds wall time. public const float DefaultCap = 150f; - private const float Step = .02f; + internal const float Step = .02f; private const float RockSeconds = 60f; private const int AmmoCheckTicks = 10; @@ -111,22 +111,20 @@ public static class EconomyLoop return samples; } - // One sortie in the demo run of this seed on one belt: the staged ship is held forty units off each rock of the belt in index - // order, fires every weapon at it, and stops when the first unit floats (the hold is full), when a starting stock runs out, or - // at the cap. Everything it touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a - // shared one advances its Random and gave the same seed different results). atEnd, if given, sees the ship, items and the processing station as the - // sample is taken, so a test can read the same state the sample was priced from. - public static LoopSample Sortie(string root, uint seed, int beltIndex, float capSeconds, Action atEnd = null) + // The demo run of one seed booted in a scratch of its own, with the two stations found by what they are for. Everything it + // touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a shared one advances its + // Random and gave the same seed different results). Dispose closes the store and deletes the scratch. + public static DemoArena Boot(string root, uint seed) { - if (!float.IsFinite(capSeconds) || capSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(capSeconds), "the cap must be a positive, finite number of sim seconds"); var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loop-" + Guid.NewGuid().ToString("N"))).FullName; + var demo = new DemoArena(scratch); try { // The catalog the game boots (the Pirates' station hulls are a package's), composed in the scratch, never written back. var composed = AetherDb.ComposeBooted(root, scratch); - using var cache = AetheriaStores.Open(composed, runPath: Path.Combine(scratch, "run.cc")); + var cache = demo.Cache = AetheriaStores.Open(composed, runPath: Path.Combine(scratch, "run.cc")); var authored = AuthoredSettings.Load(root); - var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); + var items = demo.Items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var zoneSettings = authored.Read("ZoneSettings"); var planetSettings = authored.Read("PlanetSettings"); var startingHull = File.ReadLines(Path.Combine(root, "Assets", "Resources", "Settings.asset")) @@ -137,111 +135,126 @@ public static class EconomyLoop authored.Read("SectorBackgroundSettings"), authored.Read("CastBackgroundSettings"), cache, _ => { }, null, () => seed); var galaxy = RunStart.Generate(scenario, stage); - var arena = new Zone(items, planetSettings, RunStart.GenerateArena(items, zoneSettings, planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); + var arena = demo.Arena = new Zone(items, planetSettings, RunStart.GenerateArena(items, zoneSettings, planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); var failures = new List(); - var player = RunStart.Stage(items, arena, scenario, startingHull, failures).Player; + demo.Player = RunStart.Stage(items, arena, scenario, startingHull, failures).Player; if (failures.Count > 0) throw new InvalidOperationException($"seed {seed}: staging failed: {string.Join("; ", failures)}"); - // The station that buys the sortie's ore, found by what it is for. - var processing = arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf("processing"))); - - var belts = arena.Planets.Where(body => body.Value is AsteroidBeltData).ToList(); - if (beltIndex < 0 || beltIndex >= Math.Max(belts.Count, 1)) throw new ArgumentOutOfRangeException(nameof(beltIndex), $"seed {seed} has {belts.Count} belts"); - var weapons = player.Equipment.SelectMany(item => item.Behaviors.OfType()).ToArray(); - var sample = new LoopSample - { - Seed = seed, Belt = beltIndex, Belts = belts.Count, BeltKind = "none", - Weapons = string.Join(", ", weapons.Select(w => items.GetData(w.Item.EquippableItem).Name).GroupBy(n => n).Select(g => g.Count() + "x " + g.Key)) - }; - if (belts.Count == 0) - { - sample.Outcome = LoopOutcome.RigFault; - sample.Note = "the zone holds no belt"; - return sample; - } - var belt = belts[beltIndex]; - var beltData = (AsteroidBeltData) belt.Value; - sample.BeltKind = cache.Get(beltData.Kind)?.Name ?? beltData.Kind.Key.Value; - var ammoBefore = Ammunition(items, player); - var units = 0; - arena.CargoGained.Subscribe(gain => units += gain.Stored); - - for (var tick = 0; tick < 50; tick++) arena.Update(Step); - var ticks = 0; - var capTicks = (int) Math.Round(capSeconds / Step); - var broken = 0; - var targeted = 0; - var ammoOut = false; - int? fullTick = null; - bool Stopped() => fullTick != null || ammoOut || ticks >= capTicks; - void Tick(Action hold) - { - hold(); - arena.Update(Step); - ticks++; - if (fullTick == null && arena.FloatingItems.Count > 0) fullTick = ticks; - if (ticks % AmmoCheckTicks == 0 && !ammoOut) - { - var now = Ammunition(items, player); - ammoOut = ammoBefore.Keys.Any(data => !now.ContainsKey(data)); - } - } - - for (var index = 0; index < beltData.Asteroids.Length && !Stopped(); index++) - { - var rock = new ChunkId(belt.Key, index); - if (!arena.ChunkExists(rock)) continue; - void Hold() - { - var at = arena.ChunkPose(rock.Field, rock.Index).xy; - player.Position = new float3(at.x, player.Position.y, at.y - 40f); - player.Velocity = float2.zero; - player.Direction = new float2(0, 1); - player.Aim = new float3(0, 0, 1); - } - Tick(Hold); - Tick(Hold); - if (!player.SetTarget(rock)) continue; - targeted++; - foreach (var weapon in weapons) weapon.Activate(); - for (var spent = 0; spent < (int) Math.Round(RockSeconds / Step) && arena.ChunkExists(rock) && !Stopped(); spent++) Tick(Hold); - if (!arena.ChunkExists(rock)) broken++; - } - foreach (var weapon in weapons) weapon.Deactivate(); - - var ammoAfter = Ammunition(items, player); - var spentOnAmmo = 0L; - foreach (var (data, (quantity, stack)) in ammoBefore) - { - var left = ammoAfter.TryGetValue(data, out var held) ? held.Quantity : 0; - if (quantity > left) spentOnAmmo += StationServices.BuyPrice(items, stack, quantity - left); - } - sample.Rocks = broken; - sample.SimSeconds = ticks * (double) Step; - sample.Units = units; - sample.HoldFullAt = fullTick == null ? null : fullTick * (double) Step; - sample.OfferedValue = StationServices.OreValue(items, player.CargoBays, processing); - sample.AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue); - sample.Repair = StationServices.RepairCost(items, player); - if (fullTick != null) sample.Outcome = LoopOutcome.Full; - else if (ammoOut) { sample.Outcome = LoopOutcome.AmmoOut; sample.Note = "a starting stock ran out"; } - else if (targeted == 0) { sample.Outcome = LoopOutcome.RigFault; sample.Note = "no rock of the belt could be targeted"; } - else if (ticks >= capTicks) sample.Outcome = LoopOutcome.Capped; - else { sample.Outcome = LoopOutcome.RigFault; sample.Note = "ran out of rocks before the cap"; } - atEnd?.Invoke(player, items, processing); - // The hold sells to the processing station: it pays for the units its bays take, and the rest stays aboard. - var credits = 0; - var sale = StationServices.TrySellOre(player.CargoBays, processing, ref credits); - sample.SellValue = credits; - sample.UnitsSold = sale.Sold; - sample.UnitsRefused = sale.Offered - sale.Sold; - return sample; + // The station that buys a sortie's ore and the one that holds it for onward haul, found by what they are for. + OrbitalEntity OfKind(string kind) => arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf(kind))); + demo.Processing = OfKind("processing"); + demo.Zenith = OfKind("trade-hub"); + return demo; } - finally + catch { - try { Directory.Delete(scratch, true); } catch (IOException) { } + demo.Dispose(); + throw; } } + // One sortie in the demo run of this seed on one belt: the staged ship is held forty units off each rock of the belt in index + // order, fires every weapon at it, and stops when the first unit floats (the hold is full), when a starting stock runs out, or + // at the cap. Everything it touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a + // shared one advances its Random and gave the same seed different results). atEnd, if given, sees the ship, items and the processing station as the + // sample is taken, so a test can read the same state the sample was priced from. + public static LoopSample Sortie(string root, uint seed, int beltIndex, float capSeconds, Action atEnd = null) + { + if (!float.IsFinite(capSeconds) || capSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(capSeconds), "the cap must be a positive, finite number of sim seconds"); + using var demo = Boot(root, seed); + var (cache, items, arena, player, processing) = (demo.Cache, demo.Items, demo.Arena, demo.Player, demo.Processing); + + var belts = arena.Planets.Where(body => body.Value is AsteroidBeltData).ToList(); + if (beltIndex < 0 || beltIndex >= Math.Max(belts.Count, 1)) throw new ArgumentOutOfRangeException(nameof(beltIndex), $"seed {seed} has {belts.Count} belts"); + var weapons = player.Equipment.SelectMany(item => item.Behaviors.OfType()).ToArray(); + var sample = new LoopSample + { + Seed = seed, Belt = beltIndex, Belts = belts.Count, BeltKind = "none", + Weapons = string.Join(", ", weapons.Select(w => items.GetData(w.Item.EquippableItem).Name).GroupBy(n => n).Select(g => g.Count() + "x " + g.Key)) + }; + if (belts.Count == 0) + { + sample.Outcome = LoopOutcome.RigFault; + sample.Note = "the zone holds no belt"; + return sample; + } + var belt = belts[beltIndex]; + var beltData = (AsteroidBeltData) belt.Value; + sample.BeltKind = cache.Get(beltData.Kind)?.Name ?? beltData.Kind.Key.Value; + var ammoBefore = Ammunition(items, player); + var units = 0; + arena.CargoGained.Subscribe(gain => units += gain.Stored); + + for (var tick = 0; tick < 50; tick++) arena.Update(Step); + var ticks = 0; + var capTicks = (int) Math.Round(capSeconds / Step); + var broken = 0; + var targeted = 0; + var ammoOut = false; + int? fullTick = null; + bool Stopped() => fullTick != null || ammoOut || ticks >= capTicks; + void Tick(Action hold) + { + hold(); + arena.Update(Step); + ticks++; + if (fullTick == null && arena.FloatingItems.Count > 0) fullTick = ticks; + if (ticks % AmmoCheckTicks == 0 && !ammoOut) + { + var now = Ammunition(items, player); + ammoOut = ammoBefore.Keys.Any(data => !now.ContainsKey(data)); + } + } + + for (var index = 0; index < beltData.Asteroids.Length && !Stopped(); index++) + { + var rock = new ChunkId(belt.Key, index); + if (!arena.ChunkExists(rock)) continue; + void Hold() + { + var at = arena.ChunkPose(rock.Field, rock.Index).xy; + player.Position = new float3(at.x, player.Position.y, at.y - 40f); + player.Velocity = float2.zero; + player.Direction = new float2(0, 1); + player.Aim = new float3(0, 0, 1); + } + Tick(Hold); + Tick(Hold); + if (!player.SetTarget(rock)) continue; + targeted++; + foreach (var weapon in weapons) weapon.Activate(); + for (var spent = 0; spent < (int) Math.Round(RockSeconds / Step) && arena.ChunkExists(rock) && !Stopped(); spent++) Tick(Hold); + if (!arena.ChunkExists(rock)) broken++; + } + foreach (var weapon in weapons) weapon.Deactivate(); + + var ammoAfter = Ammunition(items, player); + var spentOnAmmo = 0L; + foreach (var (data, (quantity, stack)) in ammoBefore) + { + var left = ammoAfter.TryGetValue(data, out var held) ? held.Quantity : 0; + if (quantity > left) spentOnAmmo += StationServices.BuyPrice(items, stack, quantity - left); + } + sample.Rocks = broken; + sample.SimSeconds = ticks * (double) Step; + sample.Units = units; + sample.HoldFullAt = fullTick == null ? null : fullTick * (double) Step; + sample.OfferedValue = StationServices.OreValue(items, player.CargoBays, processing); + sample.AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue); + sample.Repair = StationServices.RepairCost(items, player); + if (fullTick != null) sample.Outcome = LoopOutcome.Full; + else if (ammoOut) { sample.Outcome = LoopOutcome.AmmoOut; sample.Note = "a starting stock ran out"; } + else if (targeted == 0) { sample.Outcome = LoopOutcome.RigFault; sample.Note = "no rock of the belt could be targeted"; } + else if (ticks >= capTicks) sample.Outcome = LoopOutcome.Capped; + else { sample.Outcome = LoopOutcome.RigFault; sample.Note = "ran out of rocks before the cap"; } + atEnd?.Invoke(player, items, processing); + // The hold sells to the processing station: it pays for the units its bays take, and the rest stays aboard. + var credits = 0; + var sale = StationServices.TrySellOre(player.CargoBays, processing, ref credits); + sample.SellValue = credits; + sample.UnitsSold = sale.Sold; + sample.UnitsRefused = sale.Offered - sale.Sold; + return sample; + } // The simple commodities the hold carries that are not ore, summed per commodity: ammunition and consumables. The sampled stack carries the item the price is read from. private static Dictionary Ammunition(ItemManager items, Entity player) { @@ -321,3 +334,24 @@ public static class EconomyLoop return new LoopReport { Samples = samples, Median = median, Best = best, MedianNet = medianNet, MeasuredSorties = nets.Count, Purse = settings.StartingCredits, Ladders = ladders, Faults = faults }; } } + +// A booted demo run: the arena and what a sortie or a drain reads in it. Owns the scratch copy of the catalog and the run store. +public sealed class DemoArena : IDisposable +{ + private readonly string _scratch; + + public DemoArena(string scratch) => _scratch = scratch; + + public CultCache Cache; + public ItemManager Items; + public Zone Arena; + public Ship Player; + // The refinery that buys a sortie's ore, and the trade hub that holds ore for onward haul. + public OrbitalEntity Processing, Zenith; + + public void Dispose() + { + (Cache as IDisposable)?.Dispose(); + try { Directory.Delete(_scratch, true); } catch (IOException) { } + } +}