diff --git a/Assets/Scripts/ServerShared/EconomyBalance.cs b/Assets/Scripts/ServerShared/EconomyBalance.cs index 1c933511f..adee0a9ac 100644 --- a/Assets/Scripts/ServerShared/EconomyBalance.cs +++ b/Assets/Scripts/ServerShared/EconomyBalance.cs @@ -39,32 +39,34 @@ public sealed class BalanceReport public List Belts; } -// The static economy balance: a steady-state input-output reading of the authored chain (Leontief 1936; Sraffa 1960 zero-profit -// prices under one wage; Samuelson 1951: with labour the only primary factor the cheapest filler of a role is demand-independent). -// Pure: reads the catalog, writes nothing. Its faults are report-only and never a refusal; the authored ItemData.Price stays the -// only price the game charges. +// The static economy balance: a steady-state input-output reading of the chain (Leontief 1936; Sraffa 1960 zero-profit prices under +// one wage; Samuelson 1951: with labour the only primary factor the cheapest filler of a role is demand-independent; Lewis 1954: the +// extraction sector sets the going wage). Pure: reads the catalog, writes nothing. ItemData.Price stays the one price the game charges; +// for a made commodity it is the price Prices derives, which economy author writes. Balance's faults are report-only. public static class EconomyBalance { public const string HMargin = "H-margin", HWage = "H-wage", HConverge = "H-converge"; private const int SweepCap = 10000; - public static BalanceReport Balance(CultCache catalog, double wageSpread = 2) - { - var columns = EconomyChecks.Columns(catalog); - double Price(string key) => catalog.Get(new CultRecordKey(key))?.Price ?? 0; + // The stored price a derived price becomes: whole credits, at least 1. A chain that does not settle diverges; it reads as the largest price. + public static int Rounded(double derived) => !(derived < int.MaxValue) ? int.MaxValue : (int) Math.Max(1, Math.Round(derived, MidpointRounding.AwayFromZero)); - // Authored-price wage per link; the cheapest filler fills a role, and a role with any filler at Price 0 leaves the link unpriced. - double? CheapestPriced(string[] fillers) => fillers.Length == 0 || fillers.Any(f => Price(f) <= 0) ? (double?) null : fillers.Min(Price); + private static double Price(CultCache catalog, string key) => catalog.Get(new CultRecordKey(key))?.Price ?? 0; + + // Authored-price wage per link; the cheapest filler fills a role, and a role with any filler at Price 0 leaves the link unpriced. + private static List Links(CultCache catalog, List columns) + { + double? CheapestPriced(string[] fillers) => fillers.Length == 0 || fillers.Any(f => Price(catalog, f) <= 0) ? (double?) null : fillers.Min(f => Price(catalog, f)); var links = new List(); foreach (var c in columns) { - var link = new BalanceLink { Output = c.Output, Name = catalog.Get(c.Recipe.Output)?.Name ?? c.Output, Labour = c.Labour, Price = Price(c.Output), StationKind = catalog.Get(c.Recipe.StationKind)?.Name ?? "no kind" }; + var link = new BalanceLink { Output = c.Output, Name = catalog.Get(c.Recipe.Output)?.Name ?? c.Output, Labour = c.Labour, Price = Price(catalog, c.Output), StationKind = catalog.Get(c.Recipe.StationKind)?.Name ?? "no kind" }; var cost = 0.0; var inputsPriced = true; foreach (var (commodity, count) in c.Inputs.Concat(c.Upkeep)) { if (count <= 0) continue; - var p = Price(commodity); + var p = Price(catalog, commodity); if (p <= 0) inputsPriced = false; cost += count * p; } @@ -79,24 +81,37 @@ public static class EconomyBalance if (link.Unpriced == null) link.Wage = (c.OutputCount * link.Price - cost) / c.Labour; links.Add(link); } + return links; + } - var wages = links.Where(l => l.Wage.HasValue).Select(l => l.Wage.Value).OrderBy(w => w).ToList(); - var reference = wages.Count == 0 ? 0 : wages.Count % 2 == 1 ? wages[wages.Count / 2] : (wages[wages.Count / 2 - 1] + wages[wages.Count / 2]) / 2; - foreach (var l in links) l.WageRatio = reference > 0 ? l.Wage / reference : null; + // The going wage: the median implied wage of the priced raw links, 0 when none is priced. + private static double RawWage(CultCache catalog, List columns, List links) + { + var wages = links.Where((l, i) => l.Wage.HasValue && columns[i].IsCommodity && Recipes.IsRaw(catalog, columns[i].Recipe)).Select(l => l.Wage.Value).OrderBy(w => w).ToList(); + return wages.Count == 0 ? 0 : wages.Count % 2 == 1 ? wages[wages.Count / 2] : (wages[wages.Count / 2 - 1] + wages[wages.Count / 2]) / 2; + } - // Derived cost: value iteration from zero. A good with no recipe holds its authored price as a stand-in. + public static double Wage(CultCache catalog) + { + var columns = EconomyChecks.Columns(catalog); + return RawWage(catalog, columns, Links(catalog, columns)); + } + + // Value iteration from zero over every recipe at one wage. A good in fixedOutputs, or with no recipe, holds its authored price. + // Two recipes for one output: the cheaper sets its price, as a role takes its cheapest filler. + private static Dictionary Sweep(CultCache catalog, List columns, double wage, ISet fixedOutputs, out bool converged) + { var derived = new Dictionary(StringComparer.Ordinal); - foreach (var c in columns) derived[c.Output] = 0; - double Cost(string key) => derived.TryGetValue(key, out var v) ? v : Price(key); - var converged = false; + foreach (var c in columns) if (!fixedOutputs.Contains(c.Output)) derived[c.Output] = 0; + double Cost(string key) => derived.TryGetValue(key, out var v) ? v : Price(catalog, key); + converged = false; for (var sweep = 0; sweep < SweepCap && !converged; sweep++) { converged = true; - // Two recipes for one output: the cheaper sets its cost, as a role takes its cheapest filler. var best = new Dictionary(StringComparer.Ordinal); - foreach (var c in columns) + foreach (var c in columns.Where(c => !fixedOutputs.Contains(c.Output))) { - var sum = reference * c.Labour; + var sum = wage * c.Labour; foreach (var (commodity, count) in c.Inputs.Concat(c.Upkeep)) if (count > 0) sum += count * Cost(commodity); foreach (var slot in c.Slots) if (slot.Count > 0 && slot.Fillers.Length > 0) sum += slot.Count * slot.Fillers.Min(Cost); @@ -109,6 +124,31 @@ public static class EconomyBalance derived[output] = next; } } + return derived; + } + + // The price of every made commodity (a commodity whose recipe is not raw) at the going wage: its inputs, upkeep and cheapest + // role fillers at their prices, plus the wage times its labour, over its output count. Raw and recipeless goods keep their + // authored price; designs are not priced here. + public static Dictionary Prices(CultCache catalog) + { + var columns = EconomyChecks.Columns(catalog); + var raw = new HashSet(columns.Where(c => Recipes.IsRaw(catalog, c.Recipe)).Select(c => c.Output), StringComparer.Ordinal); + var derived = Sweep(catalog, columns, RawWage(catalog, columns, Links(catalog, columns)), raw, out _); + return columns.Where(c => c.IsCommodity && !raw.Contains(c.Output)).Select(c => c.Output).Distinct(StringComparer.Ordinal) + .ToDictionary(key => key, key => derived[key], StringComparer.Ordinal); + } + + public static BalanceReport Balance(CultCache catalog, double wageSpread = 2) + { + var columns = EconomyChecks.Columns(catalog); + var links = Links(catalog, columns); + var reference = RawWage(catalog, columns, links); + foreach (var l in links) l.WageRatio = reference > 0 ? l.Wage / reference : null; + + // Derived cost: nothing fixed, so an ore costs its labour; belt rows show price minus cost, the rent. + var derived = Sweep(catalog, columns, reference, new HashSet(), out var converged); + double Cost(string key) => derived.TryGetValue(key, out var v) ? v : Price(catalog, key); foreach (var l in links) l.Cost = derived[l.Output]; var faults = new List(); @@ -130,7 +170,7 @@ public static class EconomyBalance { var ore = y.Commodity.Key.Value; var share = y.Abundance / total; - var yield = new BeltYield { Ore = ore, Share = share, Price = Price(ore), Cost = Cost(ore), WageRatio = links.FirstOrDefault(l => l.Output == ore)?.WageRatio }; + var yield = new BeltYield { Ore = ore, Share = share, Price = Price(catalog, ore), Cost = Cost(ore), WageRatio = links.FirstOrDefault(l => l.Output == ore)?.WageRatio }; row.Price += share * yield.Price; row.Cost += share * yield.Cost; row.Yields.Add(yield); diff --git a/Assets/Scripts/ServerShared/EconomyChecks.cs b/Assets/Scripts/ServerShared/EconomyChecks.cs index d3feecd90..9e4411787 100644 --- a/Assets/Scripts/ServerShared/EconomyChecks.cs +++ b/Assets/Scripts/ServerShared/EconomyChecks.cs @@ -56,7 +56,7 @@ public sealed class EconomyReport // The one owner of the catalog's economy invariants. Pure: draws nothing, reads no clock, writes nothing. One method per rule. public static class EconomyChecks { - public const string LRecipe = "L-recipe", LOneKindList = "L-one-kind-list", LLore = "L-lore", LSource = "L-source-sink", LProductive = "L-productive", LDemand = "L-consumer-demand", LWeights = "L-weights", LShape = "L-shape"; + public const string LRecipe = "L-recipe", LOneKindList = "L-one-kind-list", LLore = "L-lore", LSource = "L-source-sink", LProductive = "L-productive", LDemand = "L-consumer-demand", LWeights = "L-weights", LShape = "L-shape", LPrice = "L-price"; private const double Margin = 1e-9; public static EconomyReport Check(CultCache catalog, EconomyLoad load = null) @@ -64,6 +64,7 @@ public static class EconomyChecks var faults = new List(); faults.AddRange(Recipe(catalog)); faults.AddRange(Shapes(catalog)); + faults.AddRange(PriceCheck(catalog)); faults.AddRange(Weights(catalog)); faults.AddRange(Lore(catalog)); faults.AddRange(SourceSink(catalog)); @@ -162,6 +163,22 @@ public static class EconomyChecks Commodities(catalog).Where(item => item.Shape?.Coordinates == null || item.Shape.Coordinates.Length == 0) .Select(item => new EconomyFault(LShape, catalog.RefOf(item).Key.Value, $"Commodity '{item.Name}' has no Shape cell: a cargo bay cannot hold it.")).ToList(); + // A made commodity's Price is the price EconomyBalance derives from its chain, rounded to whole credits (at least 1); economy author + // writes it, and a stored price off it is drift (an inspector edit) that the next author run repairs. + public static List PriceCheck(CultCache catalog) + { + var faults = new List(); + foreach (var (key, derived) in EconomyBalance.Prices(catalog).OrderBy(p => p.Key, StringComparer.Ordinal)) + { + var item = catalog.Get(new CultRecordKey(key)); + if (item == null) continue; + var want = EconomyBalance.Rounded(derived); + if (item.Price != want) + faults.Add(new EconomyFault(LPrice, key, $"Commodity '{item.Name}' is priced {item.Price}; its chain derives {want}.")); + } + return faults; + } + // Every commodity and every offered design (but a Station or Turret hull) has a recipe, and each recipe is well formed. public static List Recipe(CultCache catalog) { diff --git a/tests/Aetheria.Shared.Tests/DerivedPriceTests.cs b/tests/Aetheria.Shared.Tests/DerivedPriceTests.cs new file mode 100644 index 000000000..b284061ba --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DerivedPriceTests.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Made commodities are priced from their chain at the raw wage (EconomyBalance.Prices); economy author writes the price and L-price +// refuses drift. Fixture chains are hand-solved. +public sealed class DerivedPriceTests +{ + private sealed class Lambda : EconomyBatch + { + private readonly Action _author; + public Lambda(Action author) => _author = author; + public override void Author(EconomyAuthor author) => _author(author); + } + + private static void Price(EconomyFixture f, string key, int price) => + f.EditItem(key, item => item.Price = price); + + // ore (raw, labour 20, price 50), salt (raw, labour 10, price 100) -> raw wages 2.5 and 10, wage 6.25; + // bar (2 per cycle from 3 ore, labour 10), part (2 bars, labour 4). Authored made prices are deliberately wrong. + private static EconomyFixture Chain(int scale = 1) + { + var f = new EconomyFixture(); + f.Good("ore", workforce: 2, cycle: 10); + f.Good("salt", workforce: 1, cycle: 10); + f.Good("bar", inputs: new[] { ("ore", 3) }, outputCount: 2, workforce: 2, cycle: 5); + f.Good("part", inputs: new[] { ("bar", 2) }, workforce: 1, cycle: 4); + Price(f, "commodity:ore", 50 * scale); + Price(f, "commodity:salt", 100 * scale); + Price(f, "commodity:bar", 1); + Price(f, "commodity:part", 1); + return f; + } + + private static int Author(EconomyFixture f, bool apply, out string output, params Action[] batches) + { + f.Cache.FlushAsync().GetAwaiter().GetResult(); + var writer = new StringWriter(); + var code = EconomyCommand.Author(f.CatalogPath, batches.Select(b => (EconomyBatch) new Lambda(b)).ToList(), apply, writer, TestCatalog.Registry()); + output = writer.ToString(); + return code; + } + + private static CultCache Read(EconomyFixture f) => AetheriaStores.Open(f.CatalogPath, registry: TestCatalog.Registry()); + + [Fact] + public void AMadeGoodIsPricedAtItsInputsPlusTheRawWage() + { + using var f = Chain(); + Assert.Equal(6.25, EconomyBalance.Wage(f.Cache), 9); + var prices = EconomyBalance.Prices(f.Cache); + // bar = (3 x 50 + 6.25 x 10) / 2; the ore stays at its authored 50, not its labour cost 125. + Assert.Equal(106.25, prices["commodity:bar"], 9); + Assert.Equal(2 * 106.25 + 6.25 * 4, prices["commodity:part"], 9); + Assert.DoesNotContain("commodity:ore", prices.Keys); + } + + [Fact] + public void TheWageIsTheMedianOfRawLinks() + { + using var f = new EconomyFixture(); + f.Good("a", workforce: 1, cycle: 1); + f.Good("b", workforce: 1, cycle: 1); + f.Good("c", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("a", 1) }, workforce: 1, cycle: 1); + Price(f, "commodity:a", 1); + Price(f, "commodity:b", 2); + Price(f, "commodity:c", 10); + Price(f, "commodity:bar", 100000); + Assert.Equal(2, EconomyBalance.Wage(f.Cache), 9); + } + + [Fact] + public void RawRecipelessAndDesignPricesAreNotRepriced() + { + using var f = Chain(); + f.Cache.Upsert(typeof(SimpleCommodityData), new SimpleCommodityData { Name = "tin", Price = 7 }, new CultRecordKey("commodity:tin")); + var gear = f.Gear("laser", new[] { ("Plate", 1) }); + f.Good("plate", inputs: new[] { ("bar", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + f.EditItem(gear, g => g.Price = 12345); + Assert.Equal(0, Author(f, true, out _)); + using var after = Read(f); + Assert.Equal(50, after.Get(new CultRecordKey("commodity:ore")).Price); + Assert.Equal(100, after.Get(new CultRecordKey("commodity:salt")).Price); + Assert.Equal(7, after.Get(new CultRecordKey("commodity:tin")).Price); + Assert.Equal(12345, after.Get(new CultRecordKey(gear)).Price); + Assert.Equal(106, after.Get(new CultRecordKey("commodity:bar")).Price); + } + + [Fact] + public void AuthorRepricesAfterTheBatchesAndConverges() + { + using var f = Chain(); + // The batch sets a made good's price to 1; author runs after it and lists bar as changed, to the derived value. + Assert.Equal(0, Author(f, false, out var dry, a => a.SetPrice("commodity:bar", 1))); + Assert.Contains("changed commodity:bar", dry); + Assert.Contains("Dry run", dry); + Assert.Equal(0, Author(f, true, out _, a => a.SetPrice("commodity:bar", 1))); + using (var after = Read(f)) + { + Assert.Equal(106, after.Get(new CultRecordKey("commodity:bar")).Price); + Assert.Equal(238, after.Get(new CultRecordKey("commodity:part")).Price); + } + f.Reopen(); + Assert.Equal(0, Author(f, true, out var again)); + Assert.Contains("Nothing to write", again); + } + + [Fact] + public void AnAuthorBatchCannotKeepAMadePriceItChose() + { + using var f = Chain(); + Assert.Equal(0, Author(f, true, out _, a => a.SetPrice("commodity:part", 999999))); + using var after = Read(f); + Assert.Equal(238, after.Get(new CultRecordKey("commodity:part")).Price); + } + + [Fact] + public void AStaleMadePriceIsAnLPriceFault() + { + using var f = Chain(); + var stale = EconomyChecks.PriceCheck(f.Cache); + Assert.Equal(new[] { "commodity:bar", "commodity:part" }, stale.Select(x => x.Record).ToArray()); + Assert.All(stale, x => Assert.Equal(EconomyChecks.LPrice, x.Invariant)); + f.Settle(); + Assert.Empty(EconomyChecks.PriceCheck(f.Cache)); + // 106.25 rounds to 106 and 237.5 to 238 (half away from zero): a comparison without rounding would fault both. + Assert.Equal(106, f.Cache.Get(new CultRecordKey("commodity:bar")).Price); + Assert.Equal(238, f.Cache.Get(new CultRecordKey("commodity:part")).Price); + } + + [Fact] + public void ScalingRawPricesScalesMadePrices() + { + using var one = Chain(); + using var hundred = Chain(100); + var a = EconomyBalance.Prices(one.Cache); + var b = EconomyBalance.Prices(hundred.Cache); + foreach (var (key, price) in a) Assert.Equal(price * 100, b[key], 7); + } + + [Fact] + public void ShippedCatalogHasNoPriceFault() + { + using var cache = RestoredHullsTests.OpenCatalog(); + Assert.Empty(EconomyChecks.PriceCheck(cache)); + var prices = EconomyBalance.Prices(cache); + Assert.NotEmpty(prices); + Assert.All(prices.Keys, key => Assert.True(cache.Get(new CultRecordKey(key)).Price >= 1)); + foreach (var name in new[] { "Water", "Methane", "Diamond" }) + Assert.True(cache.GetAll().Concat(cache.GetAll()).Single(i => i.Name == name).Price > 0, name); + } +} diff --git a/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs b/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs index 4f6462aa3..fe5b03dd6 100644 --- a/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs @@ -61,10 +61,10 @@ public sealed class EconomyBalanceTests Price(f, "commodity:a-dear", 40); Price(f, "commodity:z-cheap", 30); f.EditItem(gear, g => g.Price = 100); - // Wages 10, 10, 20, 70: median 15. C: ore 15, a-dear 60, z-cheap 30, laser min(60, 30) + 15 = 45. + // The one raw link, the ore, earns 10: that is the wage. Cost: ore 10, a-dear 3 x 10 + 10 = 40, z-cheap 10 + 10 = 20, laser min(40, 20) + 10 = 30. var report = EconomyBalance.Balance(f.Cache); - Assert.Equal(15, report.WageReference, 9); - Assert.Equal(45, Link(report, gear).Cost, 9); + Assert.Equal(10, report.WageReference, 9); + Assert.Equal(30, Link(report, gear).Cost, 9); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs index e661260ab..e0f4a0eb5 100644 --- a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs @@ -517,6 +517,7 @@ public sealed class EconomyCommandTests var f = EconomyFixture.Healthy(); f.Good("loopa", inputs: new[] { ("loopb", 1) }); f.Good("loopb", inputs: new[] { ("loopa", 2) }); + f.Settle(); return f; } diff --git a/tests/Aetheria.Shared.Tests/EconomyFixture.cs b/tests/Aetheria.Shared.Tests/EconomyFixture.cs index 3aba1fe05..4ffadf90a 100644 --- a/tests/Aetheria.Shared.Tests/EconomyFixture.cs +++ b/tests/Aetheria.Shared.Tests/EconomyFixture.cs @@ -135,6 +135,17 @@ public sealed class EconomyFixture : IDisposable Rows = rows.Select(r => new OutsideMarketRow { Commodity = Item(r.Commodity), Price = 10, Buys = r.Buys, Sells = r.Sells, RatePerHour = 5 }).ToList() }, OutsideMarketData.KeyOf("gate")); + // Every made commodity at the price its chain derives, as economy author leaves it. + public void Settle() + { + foreach (var (key, derived) in EconomyBalance.Prices(Cache)) + { + var item = Cache.Get(new CultRecordKey(key)); + item.Price = EconomyBalance.Rounded(derived); + Cache.Upsert(item.GetType(), item, new CultRecordKey(key)); + } + } + // ore (raw) -> plate (fills Plate) -> a laser and a skiff that each take two plates: no fault anywhere. public static EconomyFixture Healthy() { @@ -143,6 +154,7 @@ public sealed class EconomyFixture : IDisposable f.Good("plate", inputs: new[] { ("ore", 2) }, fills: new[] { "Plate" }); f.Gear("laser", new[] { ("Plate", 2) }); f.Hull("skiff", HullType.Ship, new[] { ("Plate", 1) }); + f.Settle(); return f; } } diff --git a/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs b/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs index b348d58e3..6d2731452 100644 --- a/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs +++ b/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs @@ -61,6 +61,7 @@ public sealed class RecipeRoleInputTests public void ANullListElsewhereInARecipeLeavesItsRoleInputsToTheRules() { using var f = Smelter(); + f.Settle(); Assert.Empty(EconomyChecks.Check(f.Cache).Faults.Where(x => x.Invariant != EconomyChecks.LRecipe)); f.EditRecipe(Iron, r => r.Upkeep = null); Assert.Empty(EconomyChecks.Check(f.Cache).Faults.Where(x => x.Invariant != EconomyChecks.LRecipe)); diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 485886e0f..6b3919b8a 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -42,6 +42,14 @@ public sealed class EconomyAuthor Write(named[0].GetType(), named[0], _catalog.RefOf(named[0]).Key); } + // Sets one item's price, written under the type it is held as. + public void SetPrice(string key, int price) + { + var item = _catalog.Get(new CultRecordKey(key)); + item.Price = price; + Write(item.GetType(), item, new CultRecordKey(key)); + } + private void Write(Type type, object document, CultRecordKey key) { if (!_touched.Contains(key.Value)) _touched.Add(key.Value); @@ -60,10 +68,10 @@ public static class EconomyCommand // The invariants whose faults the batches introduce refuse them. The rest (a missing sink, no consumer demand, a commodity // with no recipe yet) are completeness: reported, and settled by the batch that closes the chain. private static readonly string[] Shape = - { EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList, EconomyChecks.LWeights, EconomyChecks.LShape }; + { 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\nbalance reads the chain and changes nothing. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor."; + private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance\nbalance reads the chain and changes nothing. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made commodity to the price its chain derives; with no batch it reprices alone."; public static int Run(string[] args, TextWriter output) { @@ -79,14 +87,14 @@ public static class EconomyCommand var spread = AuthoredSettings.Load(db.Root).Read("GameplaySettings").EconomyWageSpread; return Balance(db.Cache, spread, output); } - if (args.Length > 1 && args[0] == "author") + if (args.Length > 0 && args[0] == "author") { var apply = args.Contains("apply"); var names = args.Skip(1).Where(a => a != "apply").ToArray(); var known = typeof(EconomyBatch).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(EconomyBatch))) .OrderBy(t => t.Name, StringComparer.Ordinal).ToArray(); var unknown = names.Where(n => known.All(t => !string.Equals(t.Name, n, StringComparison.OrdinalIgnoreCase))).ToArray(); - if (unknown.Length > 0 || names.Length == 0) + if (unknown.Length > 0) { output.WriteLine($"{unknown.Length} of the names given match no batch. Batches: {string.Join(", ", known.Select(t => t.Name))}"); return 1; @@ -192,6 +200,7 @@ public static class EconomyCommand batch.Author(author); } running = ""; + Reprice(author); StationKinds.Validate(cache); } catch (Exception e) @@ -258,6 +267,16 @@ public static class EconomyCommand } } + // Every made commodity takes the price its chain derives. The one writer of a made price: batches may set any, this overwrites it. + private static void Reprice(EconomyAuthor author) + { + foreach (var (key, derived) in EconomyBalance.Prices(author.Catalog).OrderBy(p => p.Key, StringComparer.Ordinal)) + { + var price = EconomyBalance.Rounded(derived); + if (author.Catalog.Get(new CultRecordKey(key))?.Price is int held && held != price) author.SetPrice(key, price); + } + } + // Something holds Aetheria.cc open: a refusal that names the holder to close, never an exception. private static string Held(string verb, Exception e) => $"The batches are refused: Aetheria.cc could not be {verb} ({e.Message}). Something holds the file: close Unity and any other editor or tool that has it open, then run again. The catalog is unchanged.";