diff --git a/Assets/Scripts/Editor/ShipModPlaySmoke.cs b/Assets/Scripts/Editor/ShipModPlaySmoke.cs index f0753e4e6..08a849801 100644 --- a/Assets/Scripts/Editor/ShipModPlaySmoke.cs +++ b/Assets/Scripts/Editor/ShipModPlaySmoke.cs @@ -96,7 +96,7 @@ public static class ShipModPlaySmoke } Install(package.Visual.Id, Path.GetFullPath(packagePath)); - var (hull, ship) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc")); + var (hull, ship, _) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc")); ship.Id += ".broken"; hull.Name += " Broken"; hull.Visual = new CultRecordRef(ShipModCatalog.AuthoringKey(ship.Id)); diff --git a/Assets/Scripts/ServerShared/ShipAuthoring.cs b/Assets/Scripts/ServerShared/ShipAuthoring.cs index 7120d7429..42270fa6a 100644 --- a/Assets/Scripts/ServerShared/ShipAuthoring.cs +++ b/Assets/Scripts/ServerShared/ShipAuthoring.cs @@ -88,7 +88,7 @@ public static class ShipAuthoringStore var cache = new CultCache(); try { - cache.AddBackingStore(new SingleFileMessagePackBackingStore(path, !writable), new[] { typeof(HullData), typeof(ShipAuthoring) }); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(path, !writable), new[] { typeof(HullData), typeof(ShipAuthoring), typeof(FactionProductData) }); return cache; } catch @@ -105,6 +105,14 @@ public static class ShipAuthoringStore cache.UpsertAsync(typeof(ShipAuthoring), visual, ShipModCatalog.AuthoringKey(visual.Id)).GetAwaiter().GetResult(); } + // A package's product by one maker. These two are the only product writers; the key is the ship and the maker, so a + // maker has at most one product of the hull and writing again replaces it. + public static void WriteProduct(CultCache cache, string shipId, FactionProductData product) => + cache.UpsertAsync(typeof(FactionProductData), product, ShipModCatalog.ProductKey(shipId, product.Manufacturer.Key)).GetAwaiter().GetResult(); + + public static bool DeleteProduct(CultCache cache, string shipId, CultRecordKey maker) => + cache.Remove(ShipModCatalog.ProductKey(shipId, maker)); + // A new mod hull that flies like a shipped one. Every member of the reference is copied through the type's own // MessagePack round trip, so a member added to HullData later is copied too; then the six that are the shipped ship's // own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Prefab, Schematic, @@ -123,8 +131,8 @@ public static class ShipAuthoringStore } // The structure of a ship file, without judging its content (drafts load): exactly one hull and one visual, each at - // its deterministic key, the hull naming that visual by its typed ref. - public static (HullData Hull, ShipAuthoring Visual) Load(string path) + // its deterministic key, the hull naming that visual by its typed ref, and the hull's products, each at its maker's key. + public static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) Load(string path) { RefuseLegacyEmbeddedHull(path); try { return LoadRecords(path); } @@ -167,7 +175,7 @@ public static class ShipAuthoringStore private const int RetiredHullKey = 1; - private static (HullData Hull, ShipAuthoring Visual) LoadRecords(string path) + private static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) LoadRecords(string path) { using var cache = Open(path); var hulls = cache.GetAll().ToArray(); @@ -180,14 +188,38 @@ public static class ShipAuthoringStore if (!cache.TryGetHandle(hull).Value.Key.Equals(ShipModCatalog.HullKey(visual.Id)) || !cache.TryGetHandle(visual).Value.Key.Equals(ShipModCatalog.AuthoringKey(visual.Id))) throw new InvalidOperationException($"{path}: {visual.Id}: records must be stored under {ShipModCatalog.HullKey(visual.Id).Value} and {ShipModCatalog.AuthoringKey(visual.Id).Value}."); - return (hull, visual); + var products = cache.GetAll().ToArray(); + foreach (var product in products) + { + if (!product.Manufacturer.IsSet() || ShipModCatalog.IsModKey(product.Manufacturer.Key)) + throw new InvalidOperationException($"{path}: {visual.Id}: a product needs a manufacturer that is a shipped faction."); + var productKey = ShipModCatalog.ProductKey(visual.Id, product.Manufacturer.Key); + if (!cache.TryGetHandle(product).Value.Key.Equals(productKey)) + throw new InvalidOperationException($"{path}: {visual.Id}: a product must be stored at {productKey.Value}."); + if (!product.Design.IsSet() || !product.Design.Key.Equals(ShipModCatalog.HullKey(visual.Id))) + throw new InvalidOperationException($"{path}: {visual.Id}: a product must name the package hull {ShipModCatalog.HullKey(visual.Id).Value} as its design."); + } + return (hull, visual, products); } - public static (HullData Hull, ShipAuthoring Visual) Read(string path) + public static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) Read(string path) { - var (hull, visual) = Load(path); + var (hull, visual, products) = Load(path); Validate(hull, visual); - return (hull, visual); + ValidateProducts(hull, visual, products); + return (hull, visual, products); + } + + // What a package may sell: every product named, no name twice, and a price above 0, because generation skips price 0. + public static void ValidateProducts(HullData hull, ShipAuthoring visual, FactionProductData[] products) + { + if (products.Length == 0) return; + if (products.Any(product => string.IsNullOrWhiteSpace(product.Name))) + throw new InvalidOperationException($"{visual.Id}: every product needs a name."); + if (products.Select(product => product.Name).Distinct(StringComparer.Ordinal).Count() != products.Length) + throw new InvalidOperationException($"{visual.Id}: product names must be unique within the package."); + if (hull.Price <= 0) + throw new InvalidOperationException($"{visual.Id}: a hull with products needs a price above 0 (generation skips price 0)."); } // A hull names one body: a Unity prefab (shipped hulls) or a ShipAuthoring record (mod ships), never both, so no @@ -224,6 +256,8 @@ public static class ShipAuthoringStore if (hull.Shape?.Cells == null || !hull.Shape.Cells.Cast().Any(occupied => occupied)) throw new InvalidOperationException($"{ship.Id}: schematic must contain at least one cell."); RequireOneBody(hull, ship.Id); + if (hull.HullType == HullType.Ship && !(hull.Behaviors ?? new List()).Any(behavior => behavior is VelocityLimitData)) + throw new InvalidOperationException($"{ship.Id}: a ship hull needs a top speed (VelocityLimit)."); if (!hull.Visual.Key.Equals(ShipModCatalog.AuthoringKey(ship.Id))) throw new InvalidOperationException($"{ship.Id}: the hull must name its visual record {ShipModCatalog.AuthoringKey(ship.Id).Value}."); if (string.IsNullOrWhiteSpace(ship.ModelAsset) || Path.IsPathRooted(ship.ModelAsset) || diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index b997add7f..c1648bded 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -16,14 +16,18 @@ public static class ShipModCatalog public ShipAuthoring Visual; public string ModelPath; public Dictionary NodeIndices; + // The package's own products, read from its ship.cc; empty for a package taken from the catalog, where gameplay reads products. + public FactionProductData[] Products = Array.Empty(); } public static CultRecordKey HullKey(string id) => new CultRecordKey("mod-hull:" + id); public static CultRecordKey AuthoringKey(string id) => new CultRecordKey("mod-ship:" + id); + public static CultRecordKey ProductKey(string id, CultRecordKey maker) => new CultRecordKey("mod-product:" + id + ":" + maker.Value); + // A key the mods own. The shipped catalog and its authored records never reference one: a mod may be uninstalled. public static bool IsModKey(CultRecordKey key) => - key.IsSet() && (key.Value.StartsWith("mod-hull:", StringComparison.Ordinal) || key.Value.StartsWith("mod-ship:", StringComparison.Ordinal)); + key.IsSet() && (key.Value.StartsWith("mod-hull:", StringComparison.Ordinal) || key.Value.StartsWith("mod-ship:", StringComparison.Ordinal) || key.Value.StartsWith("mod-product:", StringComparison.Ordinal)); // A package left out of the composition, named by its directory, with every reason it was left out. public sealed class Exclusion @@ -93,6 +97,8 @@ public static class ShipModCatalog var keys = new HashSet(cache.AllStoredDocuments.Select(record => record.Key)); var itemNames = new HashSet(cache.GetAll().Select(item => item.Name), StringComparer.Ordinal); var shipIds = new HashSet(cache.GetAll().Select(existing => existing.Id), StringComparer.Ordinal); + var factionKeys = new HashSet(cache.GetAll().Select(faction => cache.TryGetHandle(faction).Value.Key)); + var productNames = new HashSet(cache.GetAll().Select(product => product.Name), StringComparer.Ordinal); foreach (var (directory, package) in packages) { var (hull, ship) = (package.Hull, package.Visual); @@ -102,16 +108,33 @@ public static class ShipModCatalog Exclude(directory, $"hull name '{hull.Name}' collides with an existing catalog item."); if (shipIds.Contains(ship.Id)) Exclude(directory, $"ship ID collides with an existing catalog ship authoring record."); + foreach (var product in package.Products) + { + if (!factionKeys.Contains(product.Manufacturer.Key)) + Exclude(directory, $"product '{product.Name}' names a manufacturer the shipped catalog holds no faction for."); + if (keys.Contains(ProductKey(ship.Id, product.Manufacturer.Key))) + Exclude(directory, $"a mod product key collides with an existing catalog record."); + if (productNames.Contains(product.Name)) + Exclude(directory, $"product name '{product.Name}' collides with an existing catalog product."); + } } foreach (var claim in packages.GroupBy(package => package.Package.Hull.Name, StringComparer.Ordinal).Where(group => group.Count() > 1)) foreach (var (directory, package) in claim) Exclude(directory, $"hull name '{claim.Key}' is also claimed by " + string.Join(", ", claim.Where(other => other.Directory != directory).Select(other => other.Directory)) + "."); + foreach (var claim in packages.SelectMany(package => package.Package.Products.Select(product => (package.Directory, product.Name))) + .GroupBy(entry => entry.Name, StringComparer.Ordinal).Where(group => group.Select(entry => entry.Directory).Distinct().Count() > 1)) + foreach (var directory in claim.Select(entry => entry.Directory).Distinct()) + Exclude(directory, $"product name '{claim.Key}' is also claimed by " + + string.Join(", ", claim.Select(entry => entry.Directory).Where(other => other != directory).Distinct()) + "."); var included = packages.Where(package => !reasons.ContainsKey(package.Directory)).Select(package => package.Package).ToArray(); foreach (var package in included) - // Verbatim: the mod store's own two records, under the keys it already holds them at. + { + // Verbatim: the mod store's own records, under the keys it already holds them at. ShipAuthoringStore.Write(cache, package.Hull, package.Visual); + foreach (var product in package.Products) ShipAuthoringStore.WriteProduct(cache, package.Visual.Id, product); + } // Shipped hulls too: the derived catalog must not hold a hull that names two bodies. foreach (var hull in cache.GetAll()) ShipAuthoringStore.RequireOneBody(hull, hull.Name); @@ -135,8 +158,8 @@ public static class ShipModCatalog public static Package ReadPackage(string shipPath) { var path = Path.GetFullPath(shipPath); - var (hull, ship) = ShipAuthoringStore.Read(path); - return Bind(hull, ship, Path.GetDirectoryName(path), path); + var (hull, ship, products) = ShipAuthoringStore.Read(path); + return Bind(hull, ship, products, Path.GetDirectoryName(path), path); } // The package a catalog hull names: its two records come from the catalog, and only the GLB comes from the mod @@ -147,7 +170,7 @@ public static class ShipModCatalog throw new InvalidOperationException($"{hull.Name}: the catalog holds no visual record {hull.Visual.Key.Value}."); ShipAuthoringStore.Validate(hull, ship); var directory = Path.Combine(Path.GetFullPath(modsRoot), ship.Id); - return Bind(hull, ship, directory, Path.Combine(directory, "ship.cc")); + return Bind(hull, ship, Array.Empty(), directory, Path.Combine(directory, "ship.cc")); } // The one game-side choice of catalog: the shipped file when no package is installed or none survives composition, @@ -166,7 +189,7 @@ public static class ShipModCatalog return (composition.Included.Length == 0 ? shippedCatalog : derivedCatalog, composition.Excluded); } - private static Package Bind(HullData hull, ShipAuthoring ship, string directory, string path) + private static Package Bind(HullData hull, ShipAuthoring ship, FactionProductData[] products, string directory, string path) { if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal)) throw new InvalidOperationException($"{path}: ship ID must match its package directory name."); @@ -187,7 +210,7 @@ public static class ShipModCatalog CultRecordRefs.Validate(hull); return new Package { - Hull = hull, Visual = ship, ModelPath = modelPath, + Hull = hull, Visual = ship, Products = products, ModelPath = modelPath, NodeIndices = modelNodes.ToDictionary(node => node.Key, node => node.Value.Index, StringComparer.Ordinal) }; } diff --git a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs index 0ae6b54ae..eced4c6f7 100644 --- a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs @@ -26,7 +26,7 @@ public sealed class ShipAuthoringTests ShipAuthoringStore.Write(cache, ship.Hull, ship.Visual); await cache.FlushAsync(); } - var (hull, visual) = ShipAuthoringStore.Read(path); + var (hull, visual, _) = ShipAuthoringStore.Read(path); Assert.Equal("mod.skiff", visual.Id); Assert.Equal("Skiff", hull.Name); Assert.True(hull.Shape.Cells[1, 0]); @@ -381,6 +381,7 @@ public sealed class ShipAuthoringTests { Name = "Skiff", Shape = shape, + Behaviors = { new VelocityLimitData() }, Visual = new CultRecordRef(ShipModCatalog.AuthoringKey("mod.skiff")), Hardpoints = new List { diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 7ba744cc9..721285b7b 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -89,7 +89,7 @@ public sealed class ShipModCatalogTests : IDisposable public void ComposeCopiesTheModStoresRecordsUnchangedAndTheHullNamesItsVisualByRef() { WritePackage("mod.skiff"); - var (modHull, modVisual) = ShipAuthoringStore.Read(Path.Combine(Mods, "mod.skiff", "ship.cc")); + var (modHull, modVisual, _) = ShipAuthoringStore.Read(Path.Combine(Mods, "mod.skiff", "ship.cc")); ShipModCatalog.Compose(Shipped, Derived, Mods); using var cache = AetheriaStores.Open(Derived); @@ -460,7 +460,7 @@ public sealed class ShipModCatalogTests : IDisposable foreach (var (x, y) in new[] { (0, 0), (1, 0), (2, 0), (3, 0), (0, 1) }) shape.Cells[x, y] = true; var target = Path.Combine(_directory.Path, "GameData", "Mods", "probe.l", "ship.cc"); Assert.Equal(0, Run("create", target, "probe.l", "Probe L").Code); - var (hull, ship) = ShipAuthoringStore.Load(target); + var (hull, ship, _) = ShipAuthoringStore.Load(target); hull.Shape = shape; using (var cache = ShipAuthoringStore.Open(target, writable: true)) { diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs new file mode 100644 index 000000000..a1d5c14d4 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -0,0 +1,259 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using Xunit; + +// A package carries its products (ruling package-carries-product): ship.cc homes FactionProductData at +// mod-product::, compose checks makers and names, and ship-authoring product/price write them. +// The commands read the process working directory to find GameData, so these run alone. +[Collection("process working directory")] +public sealed class ShipProductTests : IDisposable +{ + private readonly TempDirectory _root = new TempDirectory(); + private readonly string _previous = Environment.CurrentDirectory; + private readonly CultRecordKey _acme; + private readonly CultRecordKey _rival; + private string Shipped => Path.Combine(_root.Path, "GameData", "Aetheria.cc"); + private string Mods => Path.Combine(_root.Path, "GameData", "Mods"); + private string Derived => Path.Combine(_root.Path, "Derived", "Aetheria.modded.cc"); + + public ShipProductTests() + { + Directory.CreateDirectory(Mods); + Directory.CreateDirectory(Path.GetDirectoryName(Shipped)); + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + _acme = cache.Upsert(new Faction { Name = "Acme", ShortName = "ACM" }).Key; + _rival = cache.Upsert(new Faction { Name = "Rival", ShortName = "RVL" }).Key; + cache.Upsert(new Faction { Name = "Twin A", ShortName = "TWN" }); + cache.Upsert(new Faction { Name = "Twin B", ShortName = "TWN" }); + var wasp = cache.Upsert(new HullData { Name = "Wasp", Shape = ShipAuthoringTests.Fixture().Hull.Shape, Price = 10 }); + cache.Upsert(new FactionProductData + { + Name = "Taken", + Design = new CultRecordRef(wasp.Key), + Manufacturer = new CultRecordRef(_acme) + }); + cache.FlushAsync().Wait(); + } + + public void Dispose() + { + Environment.CurrentDirectory = _previous; + _root.Dispose(); + } + + private static FactionProductData Product(string name, CultRecordKey maker, string shipId) => new FactionProductData + { + Name = name, + Design = new CultRecordRef(ShipModCatalog.HullKey(shipId)), + Manufacturer = new CultRecordRef(maker) + }; + + // A valid package at Mods/, priced, selling the given products through the one product writer. + private string Package(string id, string hullName, int price, params FactionProductData[] products) + { + var directory = ShipFixture.WritePackage(Mods, id, hullName, tweak: ship => + { + ship.Hull.Price = price; + ship.Hull.Roles = new List { new ItemRole { Name = "frame" }, new ItemRole { Name = "drive" } }; + }); + var path = Path.Combine(directory, "ship.cc"); + using var cache = ShipAuthoringStore.Open(path, writable: true); + foreach (var product in products) ShipAuthoringStore.WriteProduct(cache, id, product); + cache.FlushAsync().Wait(); + return path; + } + + // A record stored where the caller says, bypassing the writer, to build the files the loader must refuse. + private static void Raw(string path, FactionProductData product, CultRecordKey key) + { + using var cache = ShipAuthoringStore.Open(path, writable: true); + cache.UpsertAsync(typeof(FactionProductData), product, key).GetAwaiter().GetResult(); + cache.FlushAsync().Wait(); + } + + [Fact] + public void ComposeCopiesEveryProductAndEachMakerIsOfferedTheHull() + { + var path = Package("mod.skiff", "Skiffhull", 100, Product("Acme Skiff", _acme, "mod.skiff"), Product("Rival Skiff", _rival, "mod.skiff")); + var (_, _, written) = ShipAuthoringStore.Read(path); + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.skiff" }, composition.Included); + using var cache = AetheriaStores.Open(Derived); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(FactionProductData).Assembly); + foreach (var (maker, name) in new[] { (_acme, "Acme Skiff"), (_rival, "Rival Skiff") }) + { + var product = cache.Get(ShipModCatalog.ProductKey("mod.skiff", maker)); + Assert.Equal(name, product.Name); + Assert.Equal(MessagePack.MessagePackSerializer.Serialize(written.Single(w => w.Name == name), options), + MessagePack.MessagePackSerializer.Serialize(product, options)); + // What LoadoutGenerator.AvailableProducts asks of a candidate: the design resolves to the hull, and it has a price. + var design = Assert.IsType(cache.Get(product.Design)); + Assert.Equal("Skiffhull", design.Name); + Assert.True(design.Price > 0); + } + } + + [Fact] + public void APackageWithAnUnknownMakerIsExcluded() + { + Package("mod.good", "Good", 100, Product("Good Skiff", _acme, "mod.good")); + Package("mod.bad", "Bad", 100, Product("Bad Skiff", new CultRecordKey("faction:nobody"), "mod.bad")); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.good" }, composition.Included); + var excluded = Assert.Single(composition.Excluded); + Assert.Equal("mod.bad", excluded.Package); + Assert.Contains("manufacturer", excluded.Reason); + } + + [Fact] + public void AProductNameCollisionExcludesThePackage() + { + Package("mod.shipped", "Shippedhull", 100, Product("Taken", _rival, "mod.shipped")); + Package("mod.a", "Ahull", 100, Product("Twin", _acme, "mod.a")); + Package("mod.b", "Bhull", 100, Product("Twin", _rival, "mod.b")); + Package("mod.fine", "Finehull", 100, Product("Fine", _acme, "mod.fine")); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.fine" }, composition.Included); + Assert.Equal(new[] { "mod.a", "mod.b", "mod.shipped" }, composition.Excluded.Select(e => e.Package).OrderBy(p => p, StringComparer.Ordinal)); + Assert.All(composition.Excluded, e => Assert.Contains("product name", e.Reason)); + } + + [Fact] + public void AProductNotAtItsMakersKeyIsRefused() + { + string Fresh(string id) => Package(id, id, 100); + void Refused(string path, string message) => + Assert.Contains(message, Assert.Throws(() => ShipAuthoringStore.Load(path)).Message); + + var misplaced = Fresh("mod.misplaced"); + Raw(misplaced, Product("P", _acme, "mod.misplaced"), new CultRecordKey("mod-product:elsewhere")); + Refused(misplaced, "must be stored at"); + + // A second product by one maker cannot be stored: the key is the maker's, so it is stored there or misplaced. + var second = Package("mod.second", "second", 100, Product("First", _acme, "mod.second")); + Raw(second, Product("Second", _acme, "mod.second"), new CultRecordKey("mod-product:mod.second:other")); + Refused(second, "must be stored at"); + + var wrongDesign = Fresh("mod.design"); + Raw(wrongDesign, Product("P", _acme, "mod.other"), ShipModCatalog.ProductKey("mod.design", _acme)); + Refused(wrongDesign, "as its design"); + + var noMaker = Fresh("mod.nomaker"); + Raw(noMaker, Product("P", default, "mod.nomaker"), new CultRecordKey("mod-product:mod.nomaker:")); + Refused(noMaker, "manufacturer"); + + var modMaker = Fresh("mod.modmaker"); + Raw(modMaker, Product("P", ShipModCatalog.HullKey("mod.x"), "mod.modmaker"), ShipModCatalog.ProductKey("mod.modmaker", ShipModCatalog.HullKey("mod.x"))); + Refused(modMaker, "manufacturer"); + + // Writing a maker's product again replaces it. + var replaced = Package("mod.replaced", "replaced", 100, Product("Old", _acme, "mod.replaced")); + using (var cache = ShipAuthoringStore.Open(replaced, writable: true)) + { + ShipAuthoringStore.WriteProduct(cache, "mod.replaced", Product("New", _acme, "mod.replaced")); + cache.FlushAsync().Wait(); + } + Assert.Equal("New", Assert.Single(ShipAuthoringStore.Load(replaced).Products).Name); + } + + [Fact] + public void ASoldPackageHullNeedsAPrice() + { + var sold = Package("mod.sold", "Sold", 0, Product("Sold Skiff", _acme, "mod.sold")); + Assert.Contains("price above 0", Assert.Throws(() => ShipAuthoringStore.Read(sold)).Message); + Assert.Single(ShipAuthoringStore.Load(sold).Products); + + Assert.Empty(ShipAuthoringStore.Read(Package("mod.console", "Console", 0)).Products); + Assert.Single(ShipAuthoringStore.Read(Package("mod.priced", "Priced", 5, Product("Priced Skiff", _acme, "mod.priced"))).Products); + } + + [Fact] + public void AnUnnamedOrDuplicatedProductNameIsRefused() + { + var blank = Package("mod.blank", "Blank", 100, Product(" ", _acme, "mod.blank")); + Assert.Contains("needs a name", Assert.Throws(() => ShipAuthoringStore.Read(blank)).Message); + var twice = Package("mod.twice", "Twice", 100, Product("Same", _acme, "mod.twice"), Product("Same", _rival, "mod.twice")); + Assert.Contains("unique", Assert.Throws(() => ShipAuthoringStore.Read(twice)).Message); + } + + [Fact] + public void AThirdKindOfRecordIsRefused() + { + var withFaction = Package("mod.faction", "Faction", 100); + var cache = new CultCache(); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(withFaction, false), + new[] { typeof(HullData), typeof(ShipAuthoring), typeof(FactionProductData), typeof(Faction) }); + using (cache) + { + cache.Upsert(new Faction { Name = "Stowaway" }); + cache.FlushAsync().Wait(); + } + Assert.Contains("no store", Assert.ThrowsAny(() => ShipAuthoringStore.Load(withFaction)).Message); + + Assert.Single(ShipAuthoringStore.Load(Package("mod.products", "Products", 100, Product("P", _acme, "mod.products"))).Products); + } + + private static (int Code, string Output, string Error) Run(params string[] args) + { + var (output, error) = (new StringWriter(), new StringWriter()); + var (previousOut, previousError) = (Console.Out, Console.Error); + Console.SetOut(output); + Console.SetError(error); + try { return (ShipAuthoringCommands.Run(args), output.ToString(), error.ToString()); } + finally { Console.SetOut(previousOut); Console.SetError(previousError); } + } + + [Fact] + public void ProductAndPriceCommands() + { + Environment.CurrentDirectory = _root.Path; + var path = Package("mod.skiff", "Skiffhull", 0); + void RefusedAndUntouched(params string[] args) + { + var before = File.ReadAllBytes(path); + Assert.Equal(1, Run(args).Code); + Assert.Equal(before, File.ReadAllBytes(path)); + } + + RefusedAndUntouched("product", path, "Nobody", "--name", "X"); + RefusedAndUntouched("product", path, "TWN", "--name", "X"); + RefusedAndUntouched("product", path, "ACM"); + RefusedAndUntouched("product", path, "ACM", "--name", " "); + RefusedAndUntouched("product", path, "ACM", "--remove"); + + var (code, _, error) = Run("product", path, "ACM", "--name", "Acme Skiff", "--description", "Reliable."); + Assert.True(code == 0, error); + var (hull, _, products) = ShipAuthoringStore.Load(path); + var product = Assert.Single(products); + using (var reopened = ShipAuthoringStore.Open(path)) + Assert.Equal(ShipModCatalog.ProductKey("mod.skiff", _acme), reopened.TryGetHandle(product).Value.Key); + Assert.Equal(_acme, product.Manufacturer.Key); + Assert.Equal(ShipModCatalog.HullKey("mod.skiff"), product.Design.Key); + Assert.Equal(hull.Roles.Select(role => role.Name), product.Roles.Select(role => role.Role)); + Assert.Equal("Reliable.", product.Description); + + // The maker by name replaces the product by short name: a maker has one product of the hull. + Assert.Equal(0, Run("product", path, "Acme", "--name", "Renamed").Code); + Assert.Equal("Renamed", Assert.Single(ShipAuthoringStore.Load(path).Products).Name); + + RefusedAndUntouched("price", path, "-1"); + RefusedAndUntouched("price", path, "1.5"); + RefusedAndUntouched("price", path, "cheap"); + Assert.Equal(0, Run("price", path, "250").Code); + Assert.Equal(250, ShipAuthoringStore.Read(path).Hull.Price); + + Assert.Equal(0, Run("product", path, "ACM", "--remove").Code); + Assert.Empty(ShipAuthoringStore.Load(path).Products); + RefusedAndUntouched("product", path, "ACM", "--remove"); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipValidationTests.cs b/tests/Aetheria.Shared.Tests/ShipValidationTests.cs index 460918608..928598b00 100644 --- a/tests/Aetheria.Shared.Tests/ShipValidationTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipValidationTests.cs @@ -15,6 +15,19 @@ public sealed class ShipValidationTests public static IEnumerable CaseNames => Cases.Keys.Select(name => new object[] { name }); + [Theory] + [InlineData(HullType.Ship, false)] + [InlineData(HullType.Station, true)] + [InlineData(HullType.Turret, true)] + public void AShipHullWithoutATopSpeedIsRefused(HullType type, bool accepted) + { + var ship = ShipAuthoringTests.Fixture(); + ship.Hull.HullType = type; + ship.Hull.Behaviors.Clear(); + if (accepted) ship.Validate(); + else Assert.Contains("top speed", Assert.Throws(() => ship.Validate()).Message); + } + [Fact] public void TheFixtureIsValid() => ShipAuthoringTests.Fixture().Validate(); diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index 60af9b39c..ce016dd16 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -8,7 +8,7 @@ using System.Linq; // Uses the existing database executable; mod authoring does not earn another binary target. public static class ShipAuthoringCommands { - private const string Usage = "ship-authoring create [--like ] | inspect | centre | validate | compose "; + private const string Usage = "ship-authoring create [--like ] | inspect | centre | validate | product (--name [--description ] | --remove) | price | compose "; public static int Run(string[] args) { @@ -28,8 +28,9 @@ public static class ShipAuthoringCommands } if (args[0] == "inspect" && args.Length == 2) { - var (hull, ship) = ShipAuthoringStore.Load(args[1]); + var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints?.Count ?? 0} hardpoints, {ship.SchematicLines?.Count ?? 0} lines, {ship.SchematicLines?.Sum(line => line.Points?.Length / 3 ?? 0) ?? 0} points"); + foreach (var product in products) Console.WriteLine($"product {product.Manufacturer.Key.Value}: {product.Name}"); return 0; } if (args[0] == "centre" && args.Length == 2) @@ -43,12 +44,16 @@ public static class ShipAuthoringCommands { // The package's GLB is judged too once it exists (node ids, mesh roles); a draft without one is judged on // its records alone, and the output says which. - var (hull, ship) = ShipAuthoringStore.Load(args[1]); + var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); var model = string.IsNullOrWhiteSpace(ship.ModelAsset) ? null : Path.Combine(Path.GetDirectoryName(Path.GetFullPath(args[1])), ship.ModelAsset); var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; if (judged == "records and model") ShipModCatalog.ReadPackage(args[1]); - else ShipAuthoringStore.Validate(hull, ship); + else + { + ShipAuthoringStore.Validate(hull, ship); + ShipAuthoringStore.ValidateProducts(hull, ship, products); + } Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {ship.SchematicLines.Count} lines ({judged})"); return 0; } @@ -75,6 +80,52 @@ public static class ShipAuthoringCommands Console.WriteLine($"Created draft {path}; fill its model bindings and schematic in Blender."); return 0; } + if (args[0] == "price" && args.Length == 3) + { + // Judged before the file is touched: a refusal leaves it byte-identical. + if (!int.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out var price)) + throw new InvalidOperationException("price must be a non-negative whole number."); + var (hull, ship, _) = ShipAuthoringStore.Load(args[1]); + hull.Price = price; + using (var cache = ShipAuthoringStore.Open(args[1], writable: true)) + { + ShipAuthoringStore.Write(cache, hull, ship); + cache.FlushAsync().Wait(); + } + Console.WriteLine($"{ship.Id}: price {price}."); + return 0; + } + if (args[0] == "product" && args.Length >= 4) + { + var remove = args.Length == 4 && args[3] == "--remove"; + var named = args.Length >= 5 && args[3] == "--name" && (args.Length == 5 || args.Length == 7 && args[5] == "--description"); + if (!remove && !named) { Console.Error.WriteLine(Usage); return 1; } + var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); + var (makerKey, makerName) = ShippedFaction(args[2]); + if (remove) + { + if (!products.Any(product => product.Manufacturer.Key.Equals(makerKey))) + throw new InvalidOperationException($"{ship.Id}: the package holds no product by that maker."); + } + else if (string.IsNullOrWhiteSpace(args[4])) + throw new InvalidOperationException("--name: a product needs a name."); + using (var cache = ShipAuthoringStore.Open(args[1], writable: true)) + { + if (remove) ShipAuthoringStore.DeleteProduct(cache, ship.Id, makerKey); + else + ShipAuthoringStore.WriteProduct(cache, ship.Id, new FactionProductData + { + Name = args[4], + Description = args.Length == 7 ? args[6] : null, + Design = new CultRecordRef(ShipModCatalog.HullKey(ship.Id)), + Manufacturer = new CultRecordRef(makerKey), + Roles = hull.Roles.Select(role => new ProductRole { Role = role.Name }).ToList() + }); + cache.FlushAsync().Wait(); + } + Console.WriteLine($"{ship.Id}: {(remove ? "removed" : "wrote")} the product by {makerName}."); + return 0; + } Console.Error.WriteLine(Usage); return 1; } @@ -85,6 +136,18 @@ public static class ShipAuthoringCommands } } + // A shipped faction by name or short name, from GameData/Aetheria.cc opened read-only: exactly one, or refused. + private static (CultRecordKey Key, string Name) ShippedFaction(string nameOrShortName) + { + using var catalog = AetherDb.Open().Cache; + var matches = catalog.GetAll() + .Where(faction => string.Equals(faction.Name, nameOrShortName, StringComparison.Ordinal) || + string.Equals(faction.ShortName, nameOrShortName, StringComparison.Ordinal)).ToArray(); + if (matches.Length != 1) + throw new InvalidOperationException($": the shipped catalog has {matches.Length} factions with that name or short name; exactly one is required."); + return (catalog.TryGetHandle(matches[0]).Value.Key, matches[0].Name); + } + // A shipped ship hull by name, from GameData/Aetheria.cc opened read-only. private static HullData ShippedShipHull(string name) {