diff --git a/tools/AetherDb/AetherDb.cs b/tools/AetherDb/AetherDb.cs index 9d7bc3e39..4a17e6b14 100644 --- a/tools/AetherDb/AetherDb.cs +++ b/tools/AetherDb/AetherDb.cs @@ -1,45 +1,32 @@ using System; using System.IO; +using GameCult.Caching; -// Opens GameData/AetherDB.msgpack through the game's own CultCache and data types, for inspection and editing. -// Close the editor's Database Tools before saving, or its next Save will overwrite what was written here. -// -// Reads do not write. That needs saying because CultCache makes it easy to get wrong: AddBackingStore subscribes -// Add to a store's EntryAdded, MultiFileBackingStore.PullAll re-emits every entry it loads, and Add pushes to the -// store registered for that type, whose Push writes a file. So registering a second store makes merely opening the -// cache rewrite its files. Name files are therefore loaded only when a command asks for them. +// Opens GameData/Aetheria.cc through AetheriaStores, the game's own store composition. The catalog attaches read-only +// unless a command writes it, so a command that only reads cannot write. public sealed class AetherDb { public string Root { get; } public CultCache Cache { get; } - private readonly SingleFileMessagePackBackingStore _store; - private AetherDb(string root, bool withNameFiles) + private AetherDb(string root, bool catalogWritable, bool withRun) { Root = root; - RegisterResolver.Register(); var gameData = Path.Combine(root, "GameData"); - _store = new SingleFileMessagePackBackingStore(Path.Combine(gameData, "AetherDB.msgpack")); - Cache = new CultCache(); - Cache.AddBackingStore(_store); - if (withNameFiles) Cache.AddBackingStore(new MultiFileMessagePackBackingStore(gameData), typeof(NameFile)); - Cache.PullAllBackingStores(); + Cache = AetheriaStores.Open( + Path.Combine(gameData, "Aetheria.cc"), + runPath: withRun ? Path.Combine(gameData, "run.cc") : null, + catalogWritable: catalogWritable); } // With no root given, walks up from the working directory to the repository - public static AetherDb Open(string root = null) => new AetherDb(root ?? FindRoot(), false); + public static AetherDb Open(bool catalogWritable = false, bool withRun = false, string root = null) => + new AetherDb(root ?? FindRoot(), catalogWritable, withRun); - // Galaxy generation needs the name files; loading them rewrites them, so only ask when they are needed, - // and not while the editor holds them open. - public static AetherDb OpenWithNameFiles(string root = null) => new AetherDb(root ?? FindRoot(), true); - - // Writes every entry back to AetherDB.msgpack, as the editor's Save button does - public void Save() => _store.PushAll(); - - private static string FindRoot() + public static string FindRoot() { for (var dir = new DirectoryInfo(Environment.CurrentDirectory); dir != null; dir = dir.Parent) - if (File.Exists(Path.Combine(dir.FullName, "GameData", "AetherDB.msgpack"))) + if (File.Exists(Path.Combine(dir.FullName, "Aetheria.Shared", "Aetheria.Shared.csproj"))) return dir.FullName; throw new DirectoryNotFoundException("Run from inside the Aetheria repository."); } diff --git a/tools/AetherDb/AetherDb.csproj b/tools/AetherDb/AetherDb.csproj index fd4c8067a..f2b488b9b 100644 --- a/tools/AetherDb/AetherDb.csproj +++ b/tools/AetherDb/AetherDb.csproj @@ -1,5 +1,5 @@ - diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 2e9ba6a93..bd5398d34 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using MessagePack; using CultMath; using Random = CultMath.Random; @@ -18,7 +17,6 @@ public static class Program var command = args.FirstOrDefault() ?? "help"; switch (command) { - case "doctor": return Doctor(); case "census": return Census(); case "station-fit": return StationFit(); case "hardpoint-fit": return HardpointFit(); @@ -28,27 +26,12 @@ public static class Program case "clear-boss-hulls": return ClearBossHulls(args.Contains("apply")); case "settings": return Settings(); case "settings-dump": return SettingsDump(); - case "migrate-products": return MigrateProducts(args.Contains("apply")); default: - Console.WriteLine("commands: doctor, census, station-fit, migrate-products [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, clear-boss-hulls [apply]"); return 1; } } - // Every entry in the database deserializes, and what types it holds. - private static int Doctor() - { - var db = AetherDb.Open(); - var bytes = File.ReadAllBytes(Path.Combine(db.Root, "GameData", "AetherDB.msgpack")); - var entries = MessagePackSerializer.Deserialize(bytes); - var nulls = entries.Select((e, i) => (e, i)).Where(x => x.e == null).Select(x => x.i).ToArray(); - Console.WriteLine($"{bytes.Length} bytes, {entries.Length} entries, {db.Cache.AllEntries.Count()} through the cache"); - Console.WriteLine(nulls.Length == 0 ? "no entries failed to deserialize" : $"FAILED at indices: {string.Join(", ", nulls)}"); - foreach (var group in entries.Where(e => e != null).GroupBy(e => e.GetType().Name).OrderBy(g => g.Key)) - Console.WriteLine($" {group.Key}: {group.Count()}"); - return nulls.Length; - } - // Designs by kind and manufacturer, designs no product sells, and products with authored role quality. private static int Census() { @@ -65,7 +48,7 @@ public static class Program : item is WeaponItemData weapon ? $"Weapon/{weapon.HardpointType}" : item.HardpointType.ToString(); if (!kinds.TryGetValue(kind, out var makers)) kinds[kind] = makers = new List(); - makers.Add(db.Cache.Get(item.Manufacturer)?.ShortName ?? "(none)"); + makers.Add(db.Cache.Get(item.Manufacturer)?.ShortName ?? "(none)"); } Console.WriteLine($"{items.Length} designs, {products.Length} products\n"); @@ -73,19 +56,23 @@ public static class Program Console.WriteLine($"{kind.Key,-22} {kind.Value.Count,3} " + string.Join(", ", kind.Value.GroupBy(m => m).OrderByDescending(g => g.Count()).Select(g => $"{g.Key}:{g.Count()}"))); - var orphans = items.Where(i => !products.Any(p => p.Design == i.ID)).ToArray(); + var sold = SoldDesigns(products); + var orphans = items.Where(i => !sold.Contains(db.Cache.RefOf(i).Key)).ToArray(); Console.WriteLine($"\n{orphans.Length} designs no product sells, so they cannot spawn:"); foreach (var item in orphans) Console.WriteLine($" {item.Name}"); var authored = products.Where(p => p.Roles != null && p.Roles.Count > 0).ToArray(); Console.WriteLine($"\n{authored.Length} products carry role quality:"); foreach (var product in authored) - Console.WriteLine($" {product.Name,-28} by {db.Cache.Get(product.Manufacturer)?.ShortName ?? "(none)",-12} " + + Console.WriteLine($" {product.Name,-28} by {db.Cache.Get(product.Manufacturer)?.ShortName ?? "(none)",-12} " + string.Join(", ", product.Roles.Select(r => $"{r.Role} {r.Mean:0.00}±{r.StandardDeviation:0.00}"))); if (authored.Length == 0) Console.WriteLine(" none yet: add roles to a design, then set each product's means"); return 0; } + private static HashSet SoldDesigns(IEnumerable products) => + new HashSet(products.Select(p => p.Design.Key)); + // Some docking bay fits every station hull, which LoadoutGenerator.GenerateStationLoadout requires. // Models the rule the game applies: an interior cell is usable when no gear occupies it, empty hardpoint // cells included. Reports both the empty hull and the case where every hardpoint is already filled, because @@ -123,7 +110,7 @@ public static class Program { var db = AetherDb.Open(); var gear = db.Cache.GetAll().ToArray(); - var products = db.Cache.GetAll().ToArray(); + var sold = SoldDesigns(db.Cache.GetAll()); var unfillable = 0; foreach (var hull in db.Cache.GetAll().OrderBy(h => h.HullType).ThenBy(h => h.Name)) { @@ -135,13 +122,13 @@ public static class Program g.HardpointType == hardpoint.Type && g.Shape.FitsWithin(hardpoint.Shape, hardpoint.Rotation, out _) && g.Shape.Coordinates.Length == cells).ToArray(); - var sold = matches.Where(m => products.Any(p => p.Design == m.ID)).ToArray(); - if (sold.Length == 0) unfillable++; - Console.WriteLine($" {hardpoint.Type,-14} {cells,2} cells: {matches.Length} designs match, {sold.Length} sold" + - (matches.Length == 0 ? " <- no design of that size" : sold.Length == 0 ? " <- designs exist but no product sells them" : "")); + var soldMatches = matches.Where(m => sold.Contains(db.Cache.RefOf(m).Key)).ToArray(); + if (soldMatches.Length == 0) unfillable++; + Console.WriteLine($" {hardpoint.Type,-14} {cells,2} cells: {matches.Length} designs match, {soldMatches.Length} sold" + + (matches.Length == 0 ? " <- no design of that size" : soldMatches.Length == 0 ? " <- designs exist but no product sells them" : "")); foreach (var match in matches) Console.WriteLine($" {match.Name,-28} {match.Shape.Coordinates.Length} cells" + - (products.Any(p => p.Design == match.ID) ? "" : " (unsold)")); + (sold.Contains(db.Cache.RefOf(match).Key) ? "" : " (unsold)")); } } Console.WriteLine($"\n{unfillable} hardpoints no product can fill"); @@ -151,7 +138,7 @@ public static class Program // The parsed shape of the settings asset, for checking where sequence items actually landed. private static int SettingsDump() { - var authored = AuthoredSettings.Load(AetherDb.Open().Root); + var authored = AuthoredSettings.Load(AetherDb.FindRoot()); authored.Dump("TutorialGenerationSettings", 2); Console.WriteLine(); authored.Dump("GameplaySettings", 2); @@ -162,8 +149,7 @@ public static class Program // anything about galaxies. Prints the values that matter to generation and every field it could not place. private static int Settings() { - var db = AetherDb.Open(); - var authored = AuthoredSettings.Load(db.Root); + var authored = AuthoredSettings.Load(AetherDb.FindRoot()); var tutorial = authored.Read("TutorialGenerationSettings"); var background = authored.Read("TutorialBackgroundSettings"); @@ -208,51 +194,53 @@ public static class Program // Clears boss hull links that resolve to nothing. Galaxy.PlaceFactionsMain gives a boss zone to every faction // carrying a BossHull, so a dangling link claims a chokepoint that can never spawn a boss. Dry run unless - // passed "apply". + // passed "apply", which alone opens the catalog writable and lands every cleared faction in one commit. private static int ClearBossHulls(bool apply) { - var db = AetherDb.Open(); + var db = AetherDb.Open(catalogWritable: apply); var dangling = db.Cache.GetAll() - .Where(f => f.BossHull != Guid.Empty && db.Cache.Get(f.BossHull) == null) + .Where(f => f.BossHull.IsSet() && db.Cache.Get(f.BossHull) == null) .OrderBy(f => f.Name) .ToArray(); Console.WriteLine($"{dangling.Length} factions point at a boss hull that does not exist:"); foreach (var faction in dangling) - { Console.WriteLine($" {faction.Name,-26} {faction.BossHull}"); - if (apply) faction.BossHull = Guid.Empty; - } if (apply && dangling.Length > 0) { - db.Save(); - Console.WriteLine($"\nCleared {dangling.Length} boss hull links in AetherDB.msgpack"); + db.Cache.Commit(batch => + { + foreach (var faction in dangling) + { + faction.BossHull = default; + batch.Upsert(faction); + } + }); + Console.WriteLine($"\nCleared {dangling.Length} boss hull links in Aetheria.cc"); } else if (!apply && dangling.Length > 0) Console.WriteLine("\nDry run. Pass \"apply\" to clear them."); return 0; } - // Each faction's generation-critical links, read through the loaded cache so the multi-file NameFile store - // counts. Galaxy.GenerateNames dereferences the geoname file without a guard, so a dangling link there stops - // galaxy generation outright. + // Each faction's generation-critical links. Galaxy.GenerateNames dereferences the geoname file without a + // guard, so an unset link there stops galaxy generation outright. private static int Factions() { - // Name files are not loaded: reporting a geoname link needs only the link's target id, and loading that - // store rewrites it. A dangling geoname therefore reads as "not loaded" here rather than as DANGLING. var db = AetherDb.Open(); var products = db.Cache.GetAll().ToArray(); Console.WriteLine($"{"faction",-26} {"short",-13} {"geonames",-22} {"boss hull",-14} {"influence",-9} products"); var broken = 0; foreach (var faction in db.Cache.GetAll().OrderBy(f => f.Name)) { - var geonames = faction.GeonameFile == Guid.Empty ? "UNSET" : "set"; - var boss = faction.BossHull == Guid.Empty + var key = db.Cache.RefOf(faction).Key; + var geonames = faction.GeonameFile.IsSet() ? "set" : "UNSET"; + var boss = !faction.BossHull.IsSet() ? "none" - : db.Cache.Get(faction.BossHull)?.Name ?? "DANGLING"; + : db.Cache.Get(faction.BossHull)?.Name ?? "DANGLING"; if (geonames == "UNSET" || boss == "DANGLING") broken++; Console.WriteLine($"{faction.Name,-26} {faction.ShortName,-13} {geonames,-22} {boss,-14} {faction.InfluenceDistance,-9} " + - products.Count(p => p.Manufacturer == faction.ID)); + products.Count(p => p.Manufacturer.Key.Equals(key))); } Console.WriteLine($"\n{broken} factions carry a link that would break generation"); return broken; @@ -263,42 +251,41 @@ public static class Program // does not repopulate it. private static int Save() { - var db = AetherDb.Open(); - var path = Path.Combine(db.Root, "GameData", "PlayerSettings.msgpack"); + var path = Path.Combine(AetherDb.FindRoot(), "GameData", "run.cc"); if (!File.Exists(path)) { Console.WriteLine($"no save at {path}"); return 0; } - PlayerSettings settings; + AetherDb db; try { - settings = MessagePackSerializer.Deserialize(File.ReadAllBytes(path)); + db = AetherDb.Open(withRun: true); } catch (Exception e) { - Console.WriteLine($"save does not deserialize: {e.GetType().Name}: {e.Message}"); + Console.WriteLine($"save does not open: {e.GetType().Name}: {e.Message}"); return 1; } - var run = settings.SavedRun; + var run = db.Cache.GetGlobal(); if (run?.Zones == null) { - Console.WriteLine($"save holds no run (player {settings.Name}, tutorial passed: {settings.TutorialPassed})"); + Console.WriteLine("run store holds no SavedGame"); return 0; } - Console.WriteLine($"player {settings.Name}, {run.Zones.Length} zones, current zone {run.CurrentZone}\n"); + Console.WriteLine($"{run.Zones.Length} zones, current zone {run.CurrentZone}\n"); var suspect = 0; for (var i = 0; i < run.Zones.Length; i++) { - var zone = run.Zones[i]; - if (zone.Contents == null) continue; + var zone = db.Cache.Get(run.Zones[i]); + if (zone?.Contents == null) continue; var stations = zone.Contents.Entities.Count(e => e is OrbitalEntityPack); var ships = zone.Contents.Entities.Count(e => e is ShipPack); var owner = zone.Owner >= 0 && zone.Owner < run.Factions.Length - ? db.Cache.Get(run.Factions[zone.Owner])?.ShortName ?? "(unknown)" + ? db.Cache.Get(run.Factions[zone.Owner])?.ShortName ?? "(unknown)" : "(none)"; var packedEmpty = zone.Contents.Orbits.Count > 0 && stations == 0; if (packedEmpty) suspect++; @@ -337,7 +324,7 @@ public static class Program { var pack = hull.HullType switch { - HullType.Ship => generator.GenerateShipLoadout(candidate => candidate.ID == hull.ID), + HullType.Ship => generator.GenerateShipLoadout(candidate => candidate == hull), HullType.Turret => generator.GenerateTurretLoadout(), _ => generator.GenerateStationLoadout() }; @@ -357,39 +344,4 @@ public static class Program Console.WriteLine($"\n{failures} hulls failed to generate a loadout (seed {seed})"); return failures; } - - // Mints a product for every design that still carries a manufacturer, copying its name and description. - private static int MigrateProducts(bool apply) - { - var db = AetherDb.Open(); - var products = db.Cache.GetAll().ToList(); - var designs = db.Cache.GetAll() - .Where(d => d.Manufacturer != Guid.Empty) - .Where(d => !products.Any(p => p.Design == d.ID && p.Manufacturer == d.Manufacturer)) - .ToArray(); - - Console.WriteLine($"{products.Count} products exist; {designs.Length} designs need one\n"); - foreach (var design in designs) - { - var product = new FactionProductData - { - Name = design.Name, - Description = design.Description, - Design = design.ID, - Manufacturer = design.Manufacturer, - // A design authored before roles existed has none; its product gets rows when roles are added - Roles = (design.Roles ?? new List()).Select(r => new ProductRole { Role = r.Name }).ToList() - }; - Console.WriteLine($" {product.Name,-28} by {db.Cache.Get(product.Manufacturer)?.ShortName ?? "(unknown)"}"); - if (apply) db.Cache.Add(product); - } - - if (apply && designs.Length > 0) - { - db.Save(); - Console.WriteLine($"\nSaved {designs.Length} products to AetherDB.msgpack"); - } - else if (!apply) Console.WriteLine("\nDry run. Pass \"apply\" to write these to the database."); - return 0; - } }