diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 906429ef8..f4f340662 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:eec42867314a3af827290c06e02d8c3f47b9c8a9a462130783181c39b58460a2 -size 277763 +oid sha256:c46adb5c23658824a2c89f552cfdd74da0488777e878cecab9f9a34adfbeefe9 +size 282124 diff --git a/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs b/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs index 10056b421..ce181f03e 100644 --- a/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs +++ b/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs @@ -219,10 +219,10 @@ public sealed class CatalogRoleTests string[] Roles(EquippableItemData d) => d.Roles.Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray(); var autocannon = Design("Autocannon"); - Assert.Equal(new[] { "barrel", "feed mechanism" }, Roles(autocannon)); - AssertRange(autocannon, "Damage", false, "barrel"); - AssertRange(autocannon, "Range", false, "barrel"); - AssertRange(autocannon, "Penetration", false, "barrel"); + Assert.Equal(new[] { "feed mechanism", "lined barrel" }, Roles(autocannon)); + AssertRange(autocannon, "Damage", false, "lined barrel"); + AssertRange(autocannon, "Range", false, "lined barrel"); + AssertRange(autocannon, "Penetration", false, "lined barrel"); var lrm = Design("Long-Range Missile Rack"); Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(lrm)); @@ -256,7 +256,7 @@ public sealed class CatalogRoleTests // Designs whose non-flat stats named no role are pointed at the role their kind's map gives them. AssertNamed(Design("Cluster Cannon"), "Count", "feed mechanism"); - AssertNamed(Design("Flak Gun"), "Count", "feed mechanism"); + AssertNamed(Design("Flak Gun"), "Count", "tracking feed"); AssertNamed(Design("Guided Missile Launcher"), "MinRange", "guidance system"); AssertNamed(Design("Lightning Projector"), "DamageSpread", "focusing array"); AssertNamed(Design("Muon Fusion Reactor"), "Modifier", "core"); diff --git a/tests/Aetheria.Shared.Tests/MunitionsBillsTests.cs b/tests/Aetheria.Shared.Tests/MunitionsBillsTests.cs new file mode 100644 index 000000000..01b888a53 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MunitionsBillsTests.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// The munitions chain's design bills (aetheria-living-world, cut design-bills-of-materials): tier role names, the four tier parts +// and the role recipes, owned by the MunitionsBills batch and not by Munitions. +public sealed class MunitionsBillsTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-bills-" + Guid.NewGuid().ToString("N")); + + public MunitionsBillsTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private string ShippedCopy(string name) + { + var path = Path.Combine(_root, name); + File.Copy(TestCatalog.Repo, path, true); + return path; + } + + private static string[] Reach(CultCache catalog, ItemData item) + { + var seen = new HashSet(StringComparer.Ordinal); + void Walk(ItemData good) + { + var recipe = Recipes.RecipeOf(catalog, good); + if (recipe == null) return; + foreach (var input in recipe.Inputs) Visit(catalog.Get(input.Commodity)); + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + foreach (var filler in Recipes.Fillers(catalog, role.Name)) Visit(catalog.Get(filler)); + } + void Visit(ItemData good) + { + if (good != null && seen.Add(catalog.RefOf(good).Key.Value)) Walk(good); + } + Walk(item); + return seen.OrderBy(k => k, StringComparer.Ordinal).ToArray(); + } + + // Kills: a bill that drops the rare inputs, or a starter whose chain reaches them. + [Fact] + public void TheTopBallisticBillReachesTheScarceMetalsAndTheStarterDoesNot() + { + using var cache = AetheriaStores.Open(TestCatalog.Repo, registry: TestCatalog.Registry()); + ItemData Gun(string name) => Assert.Single(cache.GetAll(), w => w.Name == name); + var scarce = new[] { "commodity:niobium", "commodity:rare-earth-oxides", "commodity:platinum-group-metals" }; + Assert.All(scarce, key => Assert.Contains(key, Reach(cache, Gun("Charged Scattergun")))); + Assert.All(scarce, key => Assert.DoesNotContain(key, Reach(cache, Gun("Light Machine Gun")))); + } + + // Kills: a rename that misses a stat term, a seller's profile or a bin, or one that does not converge. + [Fact] + public void RenamingARoleReachesEveryReaderAndConverges() + { + using var cache = AetheriaStores.Open(ShippedCopy("Rename.cc"), catalogWritable: true, registry: TestCatalog.Registry()); + var author = new EconomyAuthor(cache); + var rifle = Assert.Single(cache.GetAll(), w => w.Name == "Slug Rifle"); + var key = cache.RefOf(rifle).Key; + + IEnumerable TermRoles() => rifle.Behaviors.SelectMany(b => b.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)) + .SelectMany(f => ((PerformanceStat) f.GetValue(b)).Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => t.Role))); + var sellers = cache.GetAll().Where(p => p.Design.Key.Equals(key)).ToArray(); + Assert.Contains(sellers, p => p.Bin != null); + Assert.True(sellers.Count(p => p.Bin == null) >= 2); + Assert.Contains("rifled barrel", TermRoles()); + + MunitionsBills.RenameRole(author, "Slug Rifle", "rifled barrel", "barrel"); + Assert.DoesNotContain("rifled barrel", TermRoles()); + Assert.Contains("barrel", TermRoles()); + Assert.Contains("barrel", rifle.Roles.Select(r => r.Name)); + Assert.All(sellers.Where(p => p.Bin == null), p => Assert.Contains(p.Roles, r => r.Role == "barrel")); + Assert.All(sellers.Where(p => p.Bin != null), p => Assert.Empty(p.Roles)); + + MunitionsBills.RenameRole(author, "Slug Rifle", "rifled barrel", "barrel"); + MunitionsBills.RenameRole(author, "Slug Rifle", "barrel", "rifled barrel"); + Assert.DoesNotContain("barrel", TermRoles()); + Assert.All(sellers.Where(p => p.Bin == null), p => Assert.Contains(p.Roles, r => r.Role == "rifled barrel")); + } + + private sealed class DifferentGunRecipe : EconomyBatch + { + public override void Author(EconomyAuthor author) + { + var gun = author.Catalog.GetAll().Single(w => w.Name == "Autocannon"); + var key = RecipeData.KeyOf(author.Catalog.RefOf(gun).Key); + var recipe = author.Catalog.Get(key); + recipe.Workforce = 99; + author.Put(recipe, key); + } + } + + // Kills: the design-recipe block surviving in Munitions beside the bills. + [Fact] + public void MunitionsWritesNoDesignRecipe() + { + var path = ShippedCopy("Munitions.cc"); + Assert.Equal(0, EconomyCommand.Author(path, new EconomyBatch[] { new DifferentGunRecipe(), new Munitions() }, true, TextWriter.Null, TestCatalog.Registry(), _root)); + using var cache = AetheriaStores.Open(path, registry: TestCatalog.Registry()); + var gun = Assert.Single(cache.GetAll(), w => w.Name == "Autocannon"); + Assert.Equal(99, cache.Get(RecipeData.KeyOf(cache.RefOf(gun).Key)).Workforce); + } +} diff --git a/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs b/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs index 58c823af4..2630291cb 100644 --- a/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs @@ -68,12 +68,19 @@ public sealed class RolesBackfillCommandTests : IDisposable } } if (unnamed) + { + // Cluster Cannon and Flak Gun shipped before their tier roles (MunitionsBills came after the backfill). + var author = new EconomyAuthor(cache); + MunitionsBills.RenameRole(author, "Cluster Cannon", "lined barrel", "barrel"); + MunitionsBills.RenameRole(author, "Flak Gun", "tracking feed", "feed mechanism"); + designs = cache.GetAll().ToArray(); foreach (var (name, field) in Unnamed) { var design = designs.Single(d => d.Name == name); foreach (var term in Stat(design, field).Terms.Where(t => t.Source == StatSource.Quality)) term.Role = null; changed.Add(design); } + } if (changed.Count > 0) cache.Commit(batch => { @@ -107,6 +114,13 @@ public sealed class RolesBackfillCommandTests : IDisposable return string.Join("\n", new[] { roles }.Concat(stats).Concat(sellers)); } + // The tiers are history that came after the backfill, so a replay is the backfill, then the bills. + private void ApplyBills() + { + var output = new StringWriter(); + Assert.True(EconomyCommand.Author(CatalogPath, new EconomyBatch[] { new MunitionsBills() }, true, output, TestCatalog.Registry(), _root) == 0, output.ToString()); + } + private Dictionary Read() { var db = AetherDb.Open(root: _root); @@ -131,8 +145,9 @@ public sealed class RolesBackfillCommandTests : IDisposable Assert.Equal(before, File.ReadAllBytes(CatalogPath)); Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); + Assert.NotEqual(before, File.ReadAllBytes(CatalogPath)); + ApplyBills(); var landed = File.ReadAllBytes(CatalogPath); - Assert.NotEqual(before, landed); var after = Read(); foreach (var name in _shipped.Keys.OrderBy(n => n, StringComparer.Ordinal)) Assert.Equal(_shipped[name], after[name]); @@ -153,6 +168,7 @@ public sealed class RolesBackfillCommandTests : IDisposable Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); Assert.NotEqual(before, File.ReadAllBytes(CatalogPath)); + ApplyBills(); var after = Read(); foreach (var (name, _) in Unnamed) Assert.Equal(_shipped[name], after[name]); } @@ -201,7 +217,7 @@ public sealed class RolesBackfillCommandTests : IDisposable try { var after = db.Cache.GetAll().Single(p => p.Name == sellerName); - Assert.Equal(new[] { "barrel", "feed mechanism" }, after.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray()); + Assert.Equal(autocannon.Roles.Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray(), after.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray()); Assert.Equal(.91f, after.Roles.Single(r => r.Role == keptRole).Mean, 3); } finally { db.Cache.Dispose(); } diff --git a/tools/AetherDb/Economy/Munitions.cs b/tools/AetherDb/Economy/Munitions.cs index 8610b522e..5ec939658 100644 --- a/tools/AetherDb/Economy/Munitions.cs +++ b/tools/AetherDb/Economy/Munitions.cs @@ -169,12 +169,6 @@ public sealed class Munitions : EconomyBatch "Little more than steel and actuators, which is why every convoy navy can build one and every blockade starts with one.", new[] { "dispenser" }, (steel, 2), (actuator, 1)); - // The designs whose every role this chain fills. Missile racks and rocket pods also need a guidance system, which the - // electronics chain fills; their recipes wait for it. - foreach (var gun in new[] { "Light Machine Gun", "Autocannon", "Long Slug Rifle", "Charged Scattergun", "Slug Rifle", "Flak Gun", "Cluster Cannon", "Point Defense Gun" }) - Design(gun, 1800, 30, "A ballistic gun is a barrel and a feed; the round brings the energy."); - Design("Mine Launcher", 1800, 24, "A dispenser and the warheads it lays."); - // Launchers draw real rounds (ruling ballistics-real-ammo): the reactor energy per shot stays as authored, and each magazine // reload consumes one Missiles crate. foreach (var launcher in new[] { "Guided Missile Launcher", "Long-Range Missile Rack", "Short-Range Missile Rack", "Incendiary Rocket Pod", "Swarm Rocket Pod" }) @@ -267,8 +261,4 @@ public sealed class Munitions : EconomyBatch Fills = fills.ToList() }, RecipeData.KeyOf(output.Key)); } - - // A role recipe: its inputs are the design's roles, so it names none. - private void Design(string name, float cycle, int workforce, string lore) => - Recipe(Existing(name), "fabrication", cycle, workforce, 1, lore, new string[0]); } diff --git a/tools/AetherDb/Economy/MunitionsBills.cs b/tools/AetherDb/Economy/MunitionsBills.cs new file mode 100644 index 000000000..e026bf8c0 --- /dev/null +++ b/tools/AetherDb/Economy/MunitionsBills.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// Economy content, batch: the bills of the munitions chain's designs. A design recipe names roles, never components (L-roles), and a +// role is priced at its cheapest filler, so a top gun cannot be dearer than a starter by naming a rarer grade of the same role. +// It names a different role instead: a rifled barrel, a lined barrel or a coil barrel where the starter names a barrel, a tracking +// feed where it names a feed mechanism. The same stats read the renamed role, its sellers' maker profiles carry over, and a part +// built from rarer metals fills it, so the design's price climbs the ladder with its chain (rulings gear-ladder-wide-by-rare-inputs, +// top-gear-within-one-region-run). Counts, labour and the parts' metals are sim-tuned knobs (economy-numbers-are-sim-tuned-knobs). +// Missile racks and rocket pods also need a guidance system, which the electronics chain fills; their recipes wait for it. +// +// Owner of the munitions chain's design recipes, their role counts and tier role names, and the four tier parts. Munitions writes +// the parts the starter fills and the rounds; it writes no design recipe, so a Munitions rerun cannot undo a bill. Renames run +// before bills, and a design that already holds the new role name is left alone, so a rerun writes nothing. +public sealed class MunitionsBills : EconomyBatch +{ + private EconomyAuthor _a; + + public override void Author(EconomyAuthor author) + { + _a = author; + var forging = Named("Gun Forging"); + var autoloader = Named("Autoloader Mechanism"); + var diamond = Named("Diamond"); + var board = Named("Circuit Board"); + var titanium = Commodity("titanium"); + var tungsten = Commodity("tungsten"); + var niobium = Commodity("niobium"); + var rareEarth = Commodity("rare-earth-oxides"); + var pgm = Commodity("platinum-group-metals"); + + Part("rifled-barrel", "Rifled Barrel", "A forged blank bored, rifled and diamond-lined inside a titanium jacket that keeps a long tube true.", 40f, 1200, 30, "rifled barrel", + "A titanium jacket keeps a long barrel straight when one side of it is in sunlight and the other in shadow. Rifles that hit at range come from regions with a basalt crust, and a rifleman's first question about a new posting is where its titanium comes from.", + (forging, 1), (diamond, 1), (titanium, 2)); + var lined = Part("lined-barrel", "Lined Barrel", "A forged blank with a sintered tungsten liner that takes sustained fire without washing out.", 45f, 1500, 34, "lined barrel", + "Diamond lining is cheap and wears fast; tungsten lasts as long as the gun is fed. Reactors and autocannon draw on the same tungsten, so a region short of it chooses each quarter between its plasma walls and its liners.", + (forging, 1), (tungsten, 2)); + Part("coil-barrel", "Coil Barrel", "A tungsten-lined barrel wound with niobium coils and rare-earth magnets that charge the shot in the bore.", 60f, 1800, 40, "coil barrel", + "A charged scattergun carries a fusion plant's worth of niobium wound round its barrels and platinum on every contact. Only a region that holds columbite and an evolved crust, or pays the gate for them, fields these, and a squadron that does is announcing it.", + (lined, 1), (niobium, 4), (rareEarth, 2), (pgm, 1)); + Part("tracking-feed", "Tracking Feed", "An autoloader slaved to a fire-control board with platinum contacts, cycling rounds on a predicted intercept.", 35f, 1200, 30, "tracking feed", + "Point defence and flak fire on a solution, not a trigger: the feed waits for the board to say now. The platinum is there because a contact that drifts by a millisecond puts the burst behind the missile.", + (autoloader, 1), (board, 1), (pgm, 1)); + + RenameRole(_a, "Point Defense Gun", "feed mechanism", "tracking feed"); + RenameRole(_a, "Slug Rifle", "barrel", "rifled barrel"); + RenameRole(_a, "Long Slug Rifle", "barrel", "rifled barrel"); + RenameRole(_a, "Flak Gun", "feed mechanism", "tracking feed"); + RenameRole(_a, "Autocannon", "barrel", "lined barrel"); + RenameRole(_a, "Cluster Cannon", "barrel", "lined barrel"); + RenameRole(_a, "Charged Scattergun", "barrel", "coil barrel"); + + const string gun = "A ballistic gun is a barrel and a feed; the round brings the energy."; + Bill("Light Machine Gun", 30, gun, ("barrel", 1), ("feed mechanism", 1)); + Bill("Point Defense Gun", 30, gun, ("barrel", 1), ("tracking feed", 1)); + Bill("Slug Rifle", 30, gun, ("rifled barrel", 1), ("feed mechanism", 1)); + Bill("Long Slug Rifle", 40, gun, ("rifled barrel", 1), ("feed mechanism", 1)); + Bill("Flak Gun", 40, gun, ("barrel", 2), ("tracking feed", 1)); + Bill("Autocannon", 40, gun, ("lined barrel", 1), ("feed mechanism", 2)); + Bill("Cluster Cannon", 60, gun, ("lined barrel", 4), ("feed mechanism", 2)); + Bill("Charged Scattergun", 80, gun, ("coil barrel", 4), ("feed mechanism", 2)); + Bill("Mine Launcher", 24, "A dispenser and the warheads it lays.", ("dispenser", 1), ("warhead", 1)); + } + + // An item the catalog holds, by its unique name. + private CultRecordRef Named(string name) + { + var named = _a.Catalog.GetAll().Where(i => i.Name == name).ToArray(); + if (named.Length != 1) throw new InvalidOperationException($"{named.Length} items are named '{name}'; the munitions bills need exactly one."); + return new CultRecordRef(_a.Catalog.RefOf(named[0]).Key); + } + + // A metal the ores batch writes. + private CultRecordRef Commodity(string id) + { + var key = new CultRecordKey("commodity:" + id); + return _a.Catalog.Get(key) != null ? new CultRecordRef(key) : throw new InvalidOperationException($"The catalog holds no '{key.Value}'; the ores batch writes it."); + } + + // A tier part: priced by its chain (author reprices), filling only its own role. + private CultRecordRef Part(string id, string name, string description, float mass, float cycle, int workforce, string fills, string lore, + params (CultRecordRef Commodity, int Count)[] inputs) + { + var key = new CultRecordKey("commodity:" + id); + _a.Put(new CompoundCommodityData { Name = name, Description = description, Mass = mass, Price = 1 }, key); + var output = new CultRecordRef(key); + Recipe(output, cycle, workforce, lore, new[] { fills }, inputs); + return output; + } + + // Renames a role of a design everywhere it is read: the design's roles, every stat term of every behaviour, and every non-bin + // seller's profile. A design that holds the new name and not the old is left alone, so a rerun writes nothing. + public static void RenameRole(EconomyAuthor author, string design, string from, string to) + { + CultRecordKey key = default; + var pending = true; + author.Edit(design, item => + { + key = author.Catalog.RefOf(item).Key; + if (item.Roles.All(r => r.Name != from)) + { + if (item.Roles.Any(r => r.Name == to)) { pending = false; return; } + throw new InvalidOperationException($"'{design}' declares no role '{from}' to rename."); + } + foreach (var role in item.Roles.Where(r => r.Name == from)) role.Name = to; + foreach (var behavior in item.Behaviors.Where(b => b != null)) + foreach (var field in behavior.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat))) + if (field.GetValue(behavior) is PerformanceStat stat && stat.Terms != null) + foreach (var term in stat.Terms.Where(t => t.Source == StatSource.Quality && t.Role == from)) term.Role = to; + }); + if (!pending) return; + foreach (var product in author.Catalog.GetAll().Where(p => p.Bin == null && p.Design.Key.Equals(key)).ToArray()) + { + foreach (var role in product.Roles.Where(r => r.Role == from)) role.Role = to; + author.Put(product, author.Catalog.RefOf(product).Key); + } + } + + // A design's bill: each declared role's count, and the role recipe (its inputs are the roles, so it names none). + private void Bill(string design, int workforce, string lore, params (string Role, int Count)[] counts) + { + CultRecordKey key = default; + _a.Edit(design, item => + { + key = _a.Catalog.RefOf(item).Key; + foreach (var (role, count) in counts) + (item.Roles.SingleOrDefault(r => r.Name == role) ?? throw new InvalidOperationException($"'{design}' declares no role '{role}'.")).Count = count; + }); + Recipe(new CultRecordRef(key), 1800, workforce, lore, new string[0]); + } + + private void Recipe(CultRecordRef output, float cycle, int workforce, string lore, string[] fills, + params (CultRecordRef Commodity, int Count)[] inputs) + { + _a.Put(new RecipeData + { + Output = output, + OutputCount = 1, + Inputs = inputs.Select(i => new CommodityCount { Commodity = i.Commodity, Count = i.Count }).ToList(), + Cycle = cycle, + Workforce = workforce, + Upkeep = new List(), + StationKind = new CultRecordRef(StationKindData.KeyOf("fabrication")), + LoreHook = lore, + Fills = fills.ToList() + }, RecipeData.KeyOf(output.Key)); + } +}