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..e21043182 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,44 @@ 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, products) = Load(path); + ValidateLoaded(hull, visual, products); + return (hull, visual, products); + } + + // Every judgement a loaded package's records face, in one place: Read, and validate on a draft with no model yet, call it. + public static void ValidateLoaded(HullData hull, ShipAuthoring visual, FactionProductData[] products) { - var (hull, visual) = Load(path); Validate(hull, visual); - return (hull, visual); + ValidateProducts(hull, visual, products); + } + + // What a package may sell: every product named, no name twice, and a price above 0, because generation skips price 0. + private 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 +262,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/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 02c4b64a8..446bb6d89 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -162,7 +162,17 @@ keys. Each mod's stable `ShipAuthoring.Id` yields separate deterministic keys for its copied `HullData` (`mod-hull:`) and its runtime authoring record (`mod-ship:`). A mod's `ship.cc` stores its two records under those same keys, and compose copies them verbatim, so the derived catalog holds one hull -per mod ship and `HullData.Visual` names the `mod-ship` record. The generated +per mod ship and `HullData.Visual` names the `mod-ship` record. A package may +also hold the hull's products, `FactionProductData` records stored at +`mod-product::` (the third key beside `mod-hull` and +`mod-ship`; a key the mods own, never named by the shipped catalog). The key +makes a second product by one maker impossible. A ship is its maker's: the hull +carries the maker's name for it and one product by that maker, and a further +product is a rebrand by another faction (the Pirates' stolen-and-adapted +hulls). Compose copies the products verbatim and excludes a package, with a +named reason, whose product names a maker the shipped catalog holds no faction +for, or whose product name equals a shipped product's or another package's. +Blender never writes or edits a product; AetherDb does. The generated catalog is disposable; the shipped catalog and each mod's source `.cc` remain the owners. A player session opens one catalog snapshot and cannot hot-swap its designs beneath existing entities. @@ -223,7 +233,15 @@ catalog. Continue refuses a run naming a design the catalog no longer holds `aetheria.id`, is the object's `aetheria.id`. It then runs `AetherDb ship-authoring validate`, which judges the GLB too: node ids, and a mesh under every thruster and radiator anchor. The model supplies - geometry, not a second copy of hull semantics. + geometry, not a second copy of hull semantics. A ship hull needs a top + speed (a `VelocityLimitData` behavior; a station or turret does not), and + validation refuses one without. + After Package, `ship-authoring price ` sets the hull's + price and `ship-authoring product --name + [--description ]` writes the package's product by that maker + (`--remove` deletes it). A package with a product needs a price above 0, + because generation skips price 0; a package with none stays valid and is + console-only. Compose follows. 3. A command-line validator rejects malformed cells, overlapping or dangling hardpoints, missing model nodes, and unresolved asset references with precise errors. It changes no live catalog or scene on failure. The 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..f6f3bad10 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -0,0 +1,337 @@ +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 AProductKeyAlreadyInTheCatalogExcludesThePackage() + { + // A catalog record already at this ship's product key for this maker, under another name. + using (var shipped = AetheriaStores.Open(Shipped, catalogWritable: true)) + { + var held = Product("Held", _acme, "mod.keyed"); + shipped.UpsertAsync(typeof(FactionProductData), held, ShipModCatalog.ProductKey("mod.keyed", _acme)).GetAwaiter().GetResult(); + shipped.FlushAsync().Wait(); + } + using (var shipped = AetheriaStores.Open(Shipped, catalogWritable: true)) + { + var held = Product("Held Too", _rival, "mod.keyedr"); + shipped.UpsertAsync(typeof(FactionProductData), held, ShipModCatalog.ProductKey("mod.keyedr", _rival)).GetAwaiter().GetResult(); + shipped.FlushAsync().Wait(); + } + // The colliding product is one of two, and each maker takes its turn at being the colliding one, so the check + // cannot pass by looking at whichever product is listed first. + Package("mod.keyed", "Keyedhull", 100, Product("Fresh Name", _acme, "mod.keyed"), Product("Fresh Rebrand", _rival, "mod.keyed")); + Package("mod.keyedr", "Keyedrhull", 100, Product("Fresh Other", _acme, "mod.keyedr"), Product("Fresh Rival", _rival, "mod.keyedr")); + 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.keyed", "mod.keyedr" }, composition.Excluded.Select(e => e.Package).OrderBy(p => p, StringComparer.Ordinal)); + Assert.All(composition.Excluded, e => Assert.Contains("product key", e.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); + + // Below 0 is not sellable either. + var negative = Package("mod.negative", "Negative", -5, Product("Negative Skiff", _acme, "mod.negative")); + Assert.Contains("price above 0", Assert.Throws(() => ShipAuthoringStore.Read(negative)).Message); + + // The smallest sellable price: the rule is "above 0", so 1 passes. + Assert.Single(ShipAuthoringStore.Read(Package("mod.cheap", "Cheap", 1, Product("Cheap Skiff", _acme, "mod.cheap"))).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); + // The unnamed product is one of two, once under each maker, so a check of the first product alone passes neither. + foreach (var (id, unnamed, named) in new[] { ("mod.blank-acme", _acme, _rival), ("mod.blank-rival", _rival, _acme) }) + { + var second = Package(id, id, 100, Product("Named", named, id), Product(" ", unnamed, id)); + Assert.Contains("needs a name", Assert.Throws(() => ShipAuthoringStore.Read(second)).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(Assert.Single(reopened.GetAll())).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"); + } + + [Fact] + public void ValidateJudgesProductsOnADraftAndInspectListsThem() + { + Environment.CurrentDirectory = _root.Path; + // A draft is a package with no model yet: validate then judges its records alone. + string Draft(string path) + { + File.Delete(Path.Combine(Path.GetDirectoryName(path), "skiff.glb")); + return path; + } + string Refusal(string path) + { + var (code, _, error) = Run("validate", path); + Assert.Equal(1, code); + return error; + } + + Assert.Contains("price above 0", Refusal(Draft(Package("mod.free", "Free", 0, Product("Free Skiff", _acme, "mod.free"))))); + Assert.Contains("needs a name", Refusal(Draft(Package("mod.blank", "Blank", 100, Product(" ", _acme, "mod.blank"))))); + Assert.Contains("unique", Refusal(Draft(Package("mod.twice", "Twice", 100, Product("Same", _acme, "mod.twice"), Product("Same", _rival, "mod.twice"))))); + + // The hull's own rules judge a draft too: validate runs the one composition Read runs. + var unnamedHull = Draft(Path.Combine(ShipFixture.WritePackage(Mods, "mod.unnamed", hullName: ""), "ship.cc")); + Assert.Contains("hull name is required", Refusal(unnamedHull)); + + var sound = Draft(Package("mod.sound", "Sound", 100, Product("Sound Skiff", _acme, "mod.sound"), Product("Sound Rebrand", _rival, "mod.sound"))); + var (validated, output, _) = Run("validate", sound); + Assert.Equal(0, validated); + Assert.Contains("records only", output); + + var (inspected, listing, _) = Run("inspect", sound); + Assert.Equal(0, inspected); + Assert.Contains($"product {_acme.Value}: Sound Skiff", listing); + Assert.Contains($"product {_rival.Value}: Sound Rebrand", listing); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs index 452a70464..d47b418af 100644 --- a/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs @@ -33,6 +33,7 @@ public sealed class ShipSchemaPinTests { Assert.Equal(typeof(ShipAuthoring).GetCustomAttribute().SchemaName, Text("SCHEMA")); Assert.Equal(typeof(HullData).GetCustomAttribute().SchemaName, Text("HULL_SCHEMA")); + Assert.Equal(typeof(FactionProductData).GetCustomAttribute().SchemaName, Text("PRODUCT_SCHEMA")); Assert.Equal(1, Integer("RETIRED_HULL_SLOT")); // Key 1 held the embedded hull until S1. A later member must not take it, or an old file would decode as it. Assert.DoesNotContain(typeof(ShipAuthoring).GetMembers(BindingFlags.Public | BindingFlags.Instance), diff --git a/tests/Aetheria.Shared.Tests/ShipValidationTests.cs b/tests/Aetheria.Shared.Tests/ShipValidationTests.cs index 460918608..6af02ab03 100644 --- a/tests/Aetheria.Shared.Tests/ShipValidationTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipValidationTests.cs @@ -15,6 +15,20 @@ 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(); + ship.Hull.Behaviors.Add(new CapacitorData()); // a hull with other behaviors still has no top speed + 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..9fd7e690a 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,12 @@ 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.ValidateLoaded(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 +76,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 +132,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) { diff --git a/tools/blender/aetheria_ships/ship_cc.py b/tools/blender/aetheria_ships/ship_cc.py index cb76e744c..41f53601f 100644 --- a/tools/blender/aetheria_ships/ship_cc.py +++ b/tools/blender/aetheria_ships/ship_cc.py @@ -1,7 +1,8 @@ """Aetheria's Blender-side view of one ship file: a typed HullData record and the ShipAuthoring visual it names. The schemas and authority live in Aetheria's C# HullData and ShipAuthoring types. This module edits the hull's grid -and hardpoints and the visual's lines, and preserves the C# schema catalog and every slot it does not edit. Brokkr +and hardpoints and the visual's lines, and preserves the C# schema catalog and every slot it does not edit. The file +also holds the hull's products (FactionProductData records), which C# owns: every push here leaves them untouched. Brokkr supplies the Blender host and CultLib Python dependency path. """ @@ -21,6 +22,7 @@ TESTED_CULTCACHE_PY = "0.3.0" SCHEMA = "aetheria.ship_authoring" HULL_SCHEMA = "aetheria.hulldata" +PRODUCT_SCHEMA = "aetheria.factionproductdata" # MessagePack slots of the C# types, which own them (ShipAuthoring, ItemData.Shape, HullData.Hardpoints, # HardpointData). RETIRED_HULL_SLOT is the ShipAuthoring key that held the embedded hull before S1; no member owns it now. ShipSchemaPinTests in tests/Aetheria.Shared.Tests fails when any number or name below @@ -117,8 +119,10 @@ def read(path: str, cultlib_packages: str) -> ShipFile: raise ValueError( f"The ship file has a legacy embedded hull at retired key {RETIRED_HULL_SLOT} of the {SCHEMA} record; " f"migrate it into its own {HULL_SCHEMA} record that names the visual, and drop key {RETIRED_HULL_SLOT}") - if len(envelopes) != 2 or len(ships) != 1 or len(hulls) != 1: - raise ValueError(f"The ship file must hold exactly one {SCHEMA} record and one {HULL_SCHEMA} record") + products = [envelope for envelope in envelopes if envelope.type == PRODUCT_SCHEMA] + if len(ships) != 1 or len(hulls) != 1 or len(ships) + len(hulls) + len(products) != len(envelopes): + raise ValueError(f"The ship file must hold exactly one {SCHEMA} record and one {HULL_SCHEMA} record, " + f"and may hold {PRODUCT_SCHEMA} records beside them, nothing else") bodies = [] for envelope in (ships[0], hulls[0]): body = msgpack.unpackb(envelope.payload, raw=False) diff --git a/tools/blender/tests/test_ship_cc.py b/tools/blender/tests/test_ship_cc.py index f4973f9b7..b4ea9d313 100644 --- a/tools/blender/tests/test_ship_cc.py +++ b/tools/blender/tests/test_ship_cc.py @@ -97,6 +97,17 @@ class ShipFileCase(unittest.TestCase): def ship(self): return ship_cc.read(self.path, PACKAGES).ship.body + def add_products(self): + """Two products as C# stores them, one per maker; Python reads them as envelopes and never encodes one.""" + entry = catalog("product-schema-1", ship_cc.PRODUCT_SCHEMA) + store = cultcache_py.SingleFileMessagePackBackingStore(self.path) + store.push(envelope("mod-product:mod.skiff:faction:acme", ship_cc.PRODUCT_SCHEMA, entry, [None, "Acme Skiff", "Reliable."])) + store.push(envelope("mod-product:mod.skiff:faction:rival", ship_cc.PRODUCT_SCHEMA, entry, [None, "Rival Skiff", None, "tail"])) + + def products(self): + return {(e.type, e.key): e for e in cultcache_py.SingleFileMessagePackBackingStore(self.path).pull_all() + if e.type == ship_cc.PRODUCT_SCHEMA} + def hull(self): return ship_cc.read(self.path, PACKAGES).hull.body @@ -115,6 +126,12 @@ class ReadTests(ShipFileCase): self.assertEqual("Skiff", file.hull.body[1]) self.assertEqual(ship_cc.HULL_SCHEMA, file.hull.envelope.type) + def test_reads_a_file_whose_hull_also_carries_products(self): + self.add_products() + file = ship_cc.read(self.path, PACKAGES) + self.assertEqual("mod.skiff", file.ship.body[0]) + self.assertEqual("Skiff", file.hull.body[1]) + def test_refuses_a_file_with_another_record_beside_the_pair(self): cultcache_py.SingleFileMessagePackBackingStore(self.path).push(cultcache_py.CultCacheEnvelope.create( key="other", type="aetheria.something", payload=msgpack.packb([1], use_bin_type=True))) @@ -136,11 +153,18 @@ class ReadTests(ShipFileCase): with self.assertRaisesRegex(ValueError, "must hold exactly one"): ship_cc.read(self.path, PACKAGES) - def test_refuses_a_file_with_no_record(self): + def test_refuses_a_zero_byte_file_as_cultcache_does(self): + # An empty file is not a store (CultLib pins this): the owner's refusal passes through, the add-on adds none. empty = str(Path(self.path).with_name("empty.cc")) Path(empty).write_bytes(b"") - with self.assertRaisesRegex(ValueError, "must hold exactly one"): + with self.assertRaises(ValueError) as owner: + cultcache_py.SingleFileMessagePackBackingStore(empty).pull_all() + with self.assertRaises(ValueError) as raised: ship_cc.read(empty, PACKAGES) + # The very refusal cultcache-py makes, not one the add-on spells beside it (its shape refusal is a ValueError too). + self.assertIs(type(raised.exception), type(owner.exception)) + self.assertEqual(str(raised.exception), str(owner.exception)) + self.assertNotIn("must hold exactly one", str(raised.exception)) def test_refuses_a_ship_record_that_still_carries_the_retired_embedded_hull(self): for name, ship in (("nested hull", ["mod.skiff", hull_body()]), @@ -190,6 +214,33 @@ class ReadTests(ShipFileCase): ship_cc.read(self.path, PACKAGES) +class ProductCarryThroughTests(ShipFileCase): + """Products lie beside the pair, owned by C#: every push rewrites the file and leaves them byte-identical.""" + + def test_each_edit_leaves_both_product_envelopes_byte_identical(self): + self.add_products() + before = self.products() + self.assertEqual(2, len(before)) + hull = hull_body() + revision = ship_cc.layout_revision(hull[ship_cc.HULL_SHAPE_SLOT][0], hull[ship_cc.HULL_HARDPOINTS_SLOT]) + edits = ( + lambda: ship_cc.replace_lines(self.path, PACKAGES, LINES), + lambda: ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", [["map", "map-icon", "map", None, 0]]), + lambda: ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", revision, [2, 2, [True, True, True, False]], + [row[:len(ship_cc.HARDPOINT_MEMBERS)] for row in hull[ship_cc.HULL_HARDPOINTS_SLOT]]), + ) + for index, edit in enumerate(edits): + with self.subTest(edit=index): + edit() + after = self.products() + self.assertEqual(before.keys(), after.keys()) + for key in before: + self.assertEqual(before[key].payload, after[key].payload) + self.assertEqual(before[key].key, after[key].key) + # The edits really ran: the shape the layout edit wrote is in the file beside the carried products. + self.assertEqual([2, 2, [True, True, True, False]], ship_cc.read(self.path, PACKAGES).hull.body[ship_cc.HULL_SHAPE_SLOT][0]) + + class RigCarryThroughTests(ShipFileCase): """The rig (ShipAuthoring slot 5 Joints, ShipAnchor slot 5 Joint) lies past every slot this module edits, so a save keeps it."""