ship-authoring: hull, station kind and products in open/push; stats, price, kind and product become builders over the push core
DeleteProduct and the commands' direct writes are gone; hullType is checked, never written. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
767c053986
commit
7516aacb06
5 changed files with 567 additions and 151 deletions
|
|
@ -114,14 +114,11 @@ 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.
|
||||
// A package's product by one maker, written when a package is made (the key is the ship and the maker); ship-authoring push
|
||||
// is the product writer on an existing package, adds, changes and removals alike.
|
||||
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 seven that are the shipped ship's
|
||||
// own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Prefab, Schematic, Kind,
|
||||
|
|
|
|||
|
|
@ -8967,7 +8967,7 @@ in a detached worktree; anchors are file:line at b6262467.
|
|||
not a scripting surface), ship-roles-are-tags (unrelated: add-on object roles). Withdrawn
|
||||
ships-hull-material r2 and ships-hull-livery r1 are not depended on; r3 did not either.
|
||||
- Shape change from r3: Write(cache, hull, visual) is NOT widened (11 callers). A separate
|
||||
WriteProduct/DeleteProduct pair is the one product writer. Load/Read become a 3-tuple
|
||||
WriteProduct is the one product writer at creation (ship-authoring push adds, changes and removes). Load/Read become a 3-tuple
|
||||
(18 deconstruction sites in 6 files, one of them the Unity-only Editor file).
|
||||
|
||||
## Probes
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
|||
using System.IO;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
|
|
@ -63,6 +64,8 @@ public sealed class ShipAuthoringPushTests : IDisposable
|
|||
|
||||
private static string[] Listing(string path) => Directory.GetFiles(Path.GetDirectoryName(path)).Select(Path.GetFileName).OrderBy(name => name, StringComparer.Ordinal).ToArray();
|
||||
|
||||
private static byte[] Pack<T>(T value) => MessagePackSerializer.Serialize(value, CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly));
|
||||
|
||||
private static JToken Hardpoint(JObject request, string mount) => request["layout"]["hardpoints"].First(row => (string)row["mount"] == mount);
|
||||
|
||||
// Moves the gun, retargets an anchor and drops the line: the three changes the dry run and the apply must agree on.
|
||||
|
|
@ -147,13 +150,14 @@ public sealed class ShipAuthoringPushTests : IDisposable
|
|||
{
|
||||
var path = Package();
|
||||
var request = ThreeChanges(Open(path));
|
||||
// stats is a builder over the push core: it writes the hull record alone, so the ship record is still current.
|
||||
var stats = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(new[] { "stats", path, "--mass", "1" }), out _, out var statsError);
|
||||
Assert.True(stats == 0, statsError);
|
||||
var after = File.ReadAllBytes(path);
|
||||
var (code, _, outcome) = Push(path, request, apply: true);
|
||||
Assert.Equal(2, code);
|
||||
Assert.Equal("stale", (string)outcome["outcome"]);
|
||||
Assert.Equal(new[] { "mod-hull:mod.skiff", "mod-ship:mod.skiff" }, outcome["stale"].Select(key => (string)key).OrderBy(key => key, StringComparer.Ordinal));
|
||||
Assert.Equal(new[] { "mod-hull:mod.skiff" }, outcome["stale"].Select(key => (string)key).OrderBy(key => key, StringComparer.Ordinal));
|
||||
Assert.Equal(after, File.ReadAllBytes(path));
|
||||
}
|
||||
|
||||
|
|
@ -352,4 +356,260 @@ public sealed class ShipAuthoringPushTests : IDisposable
|
|||
Assert.StartsWith("refused: ", (string)outcome["verdict"]);
|
||||
Assert.Equal(7f, ShipAuthoringStore.Load(path).Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Armor);
|
||||
}
|
||||
|
||||
// ---- hull and products --------------------------------------------------------------------------------------------
|
||||
|
||||
// A shipped catalog the commands find from the working directory: factions to make products for (TWN is ambiguous)
|
||||
// and one station kind.
|
||||
private (CultRecordKey Acme, CultRecordKey TwinA) Catalog()
|
||||
{
|
||||
var shipped = Path.Combine(_root.Path, "GameData", "Aetheria.cc");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(shipped));
|
||||
using var cache = AetheriaStores.Open(shipped, catalogWritable: true);
|
||||
cache.Upsert(new VerseGrammar { Revision = 1 });
|
||||
var acme = cache.Upsert(new Faction { Name = "Acme", ShortName = "ACM" }).Key;
|
||||
cache.Upsert(new Faction { Name = "Rival", ShortName = "RVL" });
|
||||
var twin = cache.Upsert(new Faction { Name = "Twin A", ShortName = "TWN" }).Key;
|
||||
cache.Upsert(new Faction { Name = "Twin B", ShortName = "TWN" });
|
||||
cache.UpsertAsync(typeof(StationKindData), new StationKindData { Name = "Depot" }, StationKindData.KeyOf("depot")).GetAwaiter().GetResult();
|
||||
cache.FlushAsync().Wait();
|
||||
return (acme, twin);
|
||||
}
|
||||
|
||||
private static (int Code, string Output, string Error) Command(params string[] args)
|
||||
{
|
||||
var code = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(args), out var output, out var error);
|
||||
return (code, output, error);
|
||||
}
|
||||
|
||||
private static JToken Hull(JObject request) => request["hull"];
|
||||
|
||||
private static void RefusedUntouched(string path, string request, string names)
|
||||
{
|
||||
var before = File.ReadAllBytes(path);
|
||||
var files = Listing(path);
|
||||
foreach (var apply in new[] { false, true })
|
||||
{
|
||||
var (code, _, outcome) = Push(path, request, apply);
|
||||
Assert.True(code == 1, $"{names}: exit {code}: {outcome}");
|
||||
Assert.Equal("refused", (string)outcome["outcome"]);
|
||||
Assert.True(((string)outcome["message"]).Contains(names, StringComparison.Ordinal), $"{names}: {outcome["message"]}");
|
||||
Assert.Equal(before, File.ReadAllBytes(path));
|
||||
Assert.Equal(files, Listing(path));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HullFieldsRoundTripAndApply()
|
||||
{
|
||||
var path = Package();
|
||||
var opened = Open(path);
|
||||
var request = Edit(opened, json => { Hull(json)["name"] = "Renamed"; Hull(json)["price"] = 777; Hull(json)["mass"] = 4321.5f; });
|
||||
var before = File.ReadAllBytes(path);
|
||||
var (code, changes, outcome) = Push(path, request);
|
||||
Assert.Equal(0, code);
|
||||
Assert.Equal(3, changes.Length);
|
||||
Assert.Contains(changes, line => line == "mod-hull:mod.skiff name: Skiff -> Renamed");
|
||||
Assert.Contains(changes, line => line.StartsWith("mod-hull:mod.skiff price: ") && line.EndsWith(" -> 777"));
|
||||
Assert.Contains(changes, line => line.StartsWith("mod-hull:mod.skiff mass: ") && line.EndsWith(" -> 4321.5"));
|
||||
Assert.Equal(new[] { "mod-hull:mod.skiff" }, outcome["changed"].Select(key => (string)key));
|
||||
Assert.Equal(before, File.ReadAllBytes(path));
|
||||
|
||||
var (applyCode, applied, applyOutcome) = Push(path, request, apply: true);
|
||||
Assert.Equal(0, applyCode);
|
||||
Assert.Equal(changes, applied);
|
||||
var hull = ShipAuthoringStore.Load(path).Hull;
|
||||
Assert.Equal(("Renamed", 777, 4321.5f), (hull.Name, hull.Price, hull.Mass));
|
||||
var reopened = Parse(Open(path));
|
||||
Assert.Equal("Renamed", (string)Hull(reopened)["name"]);
|
||||
Assert.Equal(777, (int)Hull(reopened)["price"]);
|
||||
// The ship record was not written: its version token is the one open printed.
|
||||
Assert.Equal((string)Parse(opened)["versions"]["mod-ship:mod.skiff"], (string)reopened["versions"]["mod-ship:mod.skiff"]);
|
||||
Assert.NotEqual((string)Parse(opened)["versions"]["mod-hull:mod.skiff"], (string)reopened["versions"]["mod-hull:mod.skiff"]);
|
||||
|
||||
RefusedUntouched(path, Edit(Open(path), json => Hull(json)["price"] = -1), "price");
|
||||
RefusedUntouched(path, Edit(Open(path), json => Hull(json)["price"] = 1.5), "price");
|
||||
RefusedUntouched(path, Edit(Open(path), json => Hull(json)["mass"] = -1), "mass");
|
||||
RefusedUntouched(path, Edit(Open(path), json => Hull(json)["drag"] = -.5), "drag");
|
||||
RefusedUntouched(path, Edit(Open(path), json => Hull(json)["topSpeed"] = -1), "topSpeed");
|
||||
RefusedUntouched(path, Edit(Open(path), json => ((JObject)Hull(json)).Remove("armor")), "armor");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TopSpeedRules()
|
||||
{
|
||||
var path = Package();
|
||||
var behaviors = Pack(ShipAuthoringStore.Load(path).Hull.Behaviors);
|
||||
var opened = Parse(Open(path));
|
||||
Assert.Equal(JTokenType.Float, Hull(opened)["topSpeed"].Type);
|
||||
|
||||
// Null leaves the behaviors byte-equal.
|
||||
var (code, changes, _) = Push(path, Edit(Open(path), json => { Hull(json)["topSpeed"] = null; Hull(json)["mass"] = 9; }), apply: true);
|
||||
Assert.Equal(0, code);
|
||||
Assert.Single(changes);
|
||||
Assert.Equal(behaviors, Pack(ShipAuthoringStore.Load(path).Hull.Behaviors));
|
||||
|
||||
// A number sets Min = Max on the one VelocityLimit.
|
||||
Assert.Equal(0, Push(path, Edit(Open(path), json => Hull(json)["topSpeed"] = 42.5), apply: true).Code);
|
||||
var limit = ShipAuthoringStore.Load(path).Hull.Behaviors.OfType<VelocityLimitData>().Single().TopSpeed;
|
||||
Assert.Equal((42.5f, 42.5f), (limit.Min, limit.Max));
|
||||
Assert.Equal(42.5, (double)Hull(Parse(Open(path)))["topSpeed"]);
|
||||
|
||||
// A hull with no VelocityLimit gets one.
|
||||
var bare = Path.Combine(ShipFixture.WritePackage(Mods, "mod.bare", tweak: ship => ship.Hull.Behaviors.Clear()), "ship.cc");
|
||||
Assert.Equal(JTokenType.Null, Hull(Parse(Open(bare)))["topSpeed"].Type);
|
||||
Assert.Equal(0, Push(bare, Edit(Open(bare), json => Hull(json)["topSpeed"] = 60), apply: true).Code);
|
||||
var added = ShipAuthoringStore.Load(bare).Hull.Behaviors.OfType<VelocityLimitData>().Single().TopSpeed;
|
||||
Assert.Equal((60f, 60f), (added.Min, added.Max));
|
||||
|
||||
// Two leave no one top speed to set; open prints null for them and for a limit whose Min differs from its Max.
|
||||
var twin = Path.Combine(ShipFixture.WritePackage(Mods, "mod.twin", tweak: ship => ship.Hull.Behaviors.Add(new VelocityLimitData())), "ship.cc");
|
||||
Assert.Equal(JTokenType.Null, Hull(Parse(Open(twin)))["topSpeed"].Type);
|
||||
RefusedUntouched(twin, Edit(Open(twin), json => Hull(json)["topSpeed"] = 50), "at most one VelocityLimit");
|
||||
var ranged = Path.Combine(ShipFixture.WritePackage(Mods, "mod.ranged", tweak: ship =>
|
||||
{
|
||||
var speed = ship.Hull.Behaviors.OfType<VelocityLimitData>().Single().TopSpeed;
|
||||
speed.Min = 1;
|
||||
speed.Max = 2;
|
||||
}), "ship.cc");
|
||||
Assert.Equal(JTokenType.Null, Hull(Parse(Open(ranged)))["topSpeed"].Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProductsAddChangeRemove()
|
||||
{
|
||||
var (acme, _) = Catalog();
|
||||
var path = Package();
|
||||
var opened = Open(path);
|
||||
Assert.Empty(Parse(opened)["products"]);
|
||||
var added = Edit(opened, json => ((JArray)json["products"]).Add(new JObject { ["maker"] = "ACM", ["name"] = "Acme Skiff", ["description"] = "Reliable.", ["offered"] = true }));
|
||||
var productKey = ShipModCatalog.ProductKey("mod.skiff", acme).Value;
|
||||
var (code, changes, outcome) = Push(path, added, apply: true);
|
||||
Assert.True(code == 0, outcome.ToString());
|
||||
Assert.Equal(new[] { productKey + " added" }, changes);
|
||||
Assert.Equal(new[] { productKey }, outcome["changed"].Select(key => (string)key));
|
||||
Assert.NotNull(outcome["versions"][productKey]);
|
||||
var (hull, _, products) = ShipAuthoringStore.Load(path);
|
||||
var product = Assert.Single(products);
|
||||
Assert.Equal(ShipModCatalog.HullKey("mod.skiff"), product.Design.Key);
|
||||
Assert.Equal(acme, product.Manufacturer.Key);
|
||||
Assert.Equal(hull.Roles.Select(role => role.Name), product.Roles.Select(role => role.Role));
|
||||
Assert.Equal(("Acme Skiff", "Reliable.", false), (product.Name, product.Description, product.NotOffered));
|
||||
|
||||
// A changed name keeps the roles and the assembly no section authors.
|
||||
using (var cache = ShipAuthoringStore.Open(path, writable: true))
|
||||
{
|
||||
var held = Pack(product);
|
||||
var custom = ShipAuthoringPush.Copy(product);
|
||||
custom.Roles = new List<ProductRole> { new ProductRole { Role = "special", Mean = .9f } };
|
||||
custom.Assembly = new AssemblyDistribution { Mean = .8f };
|
||||
ShipAuthoringStore.WriteProduct(cache, "mod.skiff", custom);
|
||||
cache.FlushAsync().Wait();
|
||||
Assert.NotEqual(held, Pack(custom));
|
||||
}
|
||||
var opened2 = Open(path);
|
||||
Assert.Equal(acme.Value, (string)Parse(opened2)["products"][0]["maker"]);
|
||||
var renamed = Edit(opened2, json => { json["products"][0]["name"] = "Acme Racer"; json["products"][0]["offered"] = false; });
|
||||
var (renameCode, renameChanges, _) = Push(path, renamed, apply: true);
|
||||
Assert.Equal(0, renameCode);
|
||||
Assert.Equal(new[] { productKey + " name: Acme Skiff -> Acme Racer", productKey + " offered: true -> false" }, renameChanges);
|
||||
var kept = Assert.Single(ShipAuthoringStore.Load(path).Products);
|
||||
Assert.Equal(("Acme Racer", true), (kept.Name, kept.NotOffered));
|
||||
Assert.Equal("special", Assert.Single(kept.Roles).Role);
|
||||
Assert.Equal(.8f, kept.Assembly.Mean);
|
||||
|
||||
// A dropped row removes the record, with a hull change in the same commit.
|
||||
var removed = Edit(Open(path), json => { ((JArray)json["products"]).Clear(); Hull(json)["price"] = 5; });
|
||||
var (removeCode, removeChanges, removeOutcome) = Push(path, removed, apply: true);
|
||||
Assert.Equal(0, removeCode);
|
||||
Assert.Contains(productKey + " removed", removeChanges);
|
||||
Assert.Equal(new[] { "mod-hull:mod.skiff", productKey }, removeOutcome["changed"].Select(key => (string)key).OrderBy(key => key, StringComparer.Ordinal));
|
||||
Assert.Empty(ShipAuthoringStore.Load(path).Products);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProductMakerResolution()
|
||||
{
|
||||
var (_, twinA) = Catalog();
|
||||
var path = Package();
|
||||
ProductRowEdit(path, "Nobody", "X", "0 factions");
|
||||
ProductRowEdit(path, "TWN", "X", "2 factions");
|
||||
ProductRowEdit(path, "ACM", " ", "needs a name");
|
||||
RefusedUntouched(path, Edit(Open(path), json =>
|
||||
{
|
||||
((JArray)json["products"]).Add(new JObject { ["maker"] = "ACM", ["name"] = "A", ["description"] = null, ["offered"] = true });
|
||||
((JArray)json["products"]).Add(new JObject { ["maker"] = "Acme", ["name"] = "B", ["description"] = null, ["offered"] = true });
|
||||
}), "Acme");
|
||||
|
||||
// A stored maker's key names its product with no resolution through the catalog's names (TWN is ambiguous there).
|
||||
using (var cache = ShipAuthoringStore.Open(path, writable: true))
|
||||
{
|
||||
ShipAuthoringStore.WriteProduct(cache, "mod.skiff", new FactionProductData
|
||||
{
|
||||
Name = "Twin Skiff",
|
||||
Design = new CultRecordRef<CraftedItemData>(ShipModCatalog.HullKey("mod.skiff")),
|
||||
Manufacturer = new CultRecordRef<Faction>(twinA)
|
||||
});
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
var request = Edit(Open(path), json => json["products"][0]["name"] = "Twin Racer");
|
||||
Assert.Equal(twinA.Value, (string)Parse(request)["products"][0]["maker"]);
|
||||
Assert.Equal(0, Push(path, request, apply: true).Code);
|
||||
Assert.Equal("Twin Racer", Assert.Single(ShipAuthoringStore.Load(path).Products).Name);
|
||||
}
|
||||
|
||||
private void ProductRowEdit(string path, string maker, string name, string message) =>
|
||||
RefusedUntouched(path, Edit(Open(path), json => ((JArray)json["products"]).Add(
|
||||
new JObject { ["maker"] = maker, ["name"] = name, ["description"] = null, ["offered"] = true })), message);
|
||||
|
||||
// A new product's key is expected absent: one written since the open makes the push stale.
|
||||
[Fact]
|
||||
public void NewProductExpectsAbsent()
|
||||
{
|
||||
var (acme, _) = Catalog();
|
||||
var path = Package();
|
||||
var request = Edit(Open(path), json => ((JArray)json["products"]).Add(new JObject { ["maker"] = "ACM", ["name"] = "Mine", ["description"] = null, ["offered"] = true }));
|
||||
var (code, _, error) = Command("product", path, "ACM", "--name", "Theirs");
|
||||
Assert.True(code == 0, error);
|
||||
var after = File.ReadAllBytes(path);
|
||||
var (pushCode, _, outcome) = Push(path, request, apply: true);
|
||||
Assert.Equal(2, pushCode);
|
||||
Assert.Equal("stale", (string)outcome["outcome"]);
|
||||
Assert.Equal(new[] { ShipModCatalog.ProductKey("mod.skiff", acme).Value }, outcome["stale"].Select(key => (string)key));
|
||||
Assert.Equal(after, File.ReadAllBytes(path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HullTypeChecked()
|
||||
{
|
||||
var path = Package();
|
||||
var open = Open(path);
|
||||
Assert.Equal("Ship", (string)Parse(open)["hullType"]);
|
||||
RefusedUntouched(path, Edit(open, json => json["hullType"] = "Station"), "hullType");
|
||||
var without = Edit(open, json => json.Remove("hullType"));
|
||||
Assert.Equal(0, Push(path, without, apply: true).Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KindInHullSection()
|
||||
{
|
||||
Catalog();
|
||||
var target = Path.Combine(ShipFixture.WritePackage(Mods, "probe.depot", "Probe Depot", tweak: ship => ship.Hull.HullType = HullType.Station), "ship.cc");
|
||||
Assert.Equal(JTokenType.Null, Hull(Parse(Open(target)))["kind"].Type);
|
||||
|
||||
// A stats push on a kindless station applies: the kind is only judged when it changes.
|
||||
Assert.Equal(0, Push(target, Edit(Open(target), json => Hull(json)["mass"] = 11), apply: true).Code);
|
||||
Assert.Equal(11f, ShipAuthoringStore.Load(target).Hull.Mass);
|
||||
Assert.Equal(0, Command("price", target, "12").Code);
|
||||
|
||||
RefusedUntouched(target, Edit(Open(target), json => Hull(json)["kind"] = "station-kind:nowhere"), "names no station kind");
|
||||
var (code, _, error) = Command("kind", target, "depot");
|
||||
Assert.True(code == 0, error);
|
||||
Assert.Equal("station-kind:depot", (string)Hull(Parse(Open(target)))["kind"]);
|
||||
// A station with no kind is refused: clearing one is.
|
||||
RefusedUntouched(target, Edit(Open(target), json => Hull(json)["kind"] = null), "has no Kind");
|
||||
|
||||
var ship = Package();
|
||||
RefusedUntouched(ship, Edit(Open(ship), json => Hull(json)["kind"] = "station-kind:depot"), "only a station hull has one");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,15 +120,7 @@ public static class ShipAuthoringCommands
|
|||
// 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;
|
||||
return Build(args[1], request => request.Hull.Price = price, ship => $"{ship}: price {price}.");
|
||||
}
|
||||
if (args[0] == "stats" && args.Length >= 2)
|
||||
{
|
||||
|
|
@ -144,31 +136,15 @@ public static class ShipAuthoringCommands
|
|||
stats[args[i]] = value;
|
||||
}
|
||||
if (stats.Count == 0) throw new InvalidOperationException("stats: name at least one stat.");
|
||||
var (hull, ship, _) = ShipAuthoringStore.Load(args[1]);
|
||||
if (stats.TryGetValue("--top-speed", out var topSpeed))
|
||||
// The push core owns the VelocityLimit rules: the one top speed, the add on a hull with none, the refusal of twins.
|
||||
return Build(args[1], request =>
|
||||
{
|
||||
var limits = (hull.Behaviors ?? new List<BehaviorData>()).OfType<VelocityLimitData>().ToArray();
|
||||
if (limits.Length > 1) throw new InvalidOperationException($"{ship.Id}: --top-speed needs at most one VelocityLimit on the hull; it has {limits.Length}.");
|
||||
// A hull made without --like has none, and this is its only way to get one: validate refuses a ship without a top speed.
|
||||
if (limits.Length == 0)
|
||||
{
|
||||
limits = new[] { new VelocityLimitData() };
|
||||
(hull.Behaviors ??= new List<BehaviorData>()).Add(limits[0]);
|
||||
}
|
||||
// A fixed top speed, as every shipped hull authors one (Min equal to Max); its terms are kept.
|
||||
limits[0].TopSpeed.Min = limits[0].TopSpeed.Max = topSpeed;
|
||||
}
|
||||
if (stats.TryGetValue("--mass", out var mass)) hull.Mass = mass;
|
||||
if (stats.TryGetValue("--durability", out var durability)) hull.Durability = durability;
|
||||
if (stats.TryGetValue("--armor", out var armor)) hull.Armor = armor;
|
||||
if (stats.TryGetValue("--drag", out var drag)) hull.Drag = drag;
|
||||
using (var cache = ShipAuthoringStore.Open(args[1], writable: true))
|
||||
{
|
||||
ShipAuthoringStore.Write(cache, hull, ship);
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
Console.WriteLine($"{ship.Id}: " + string.Join(", ", stats.Select(stat => string.Create(CultureInfo.InvariantCulture, $"{stat.Key.Substring(2)} {stat.Value:R}"))) + ".");
|
||||
return 0;
|
||||
if (stats.TryGetValue("--top-speed", out var topSpeed)) request.Hull.TopSpeed = topSpeed;
|
||||
if (stats.TryGetValue("--mass", out var mass)) request.Hull.Mass = mass;
|
||||
if (stats.TryGetValue("--durability", out var durability)) request.Hull.Durability = durability;
|
||||
if (stats.TryGetValue("--armor", out var armor)) request.Hull.Armor = armor;
|
||||
if (stats.TryGetValue("--drag", out var drag)) request.Hull.Drag = drag;
|
||||
}, ship => $"{ship}: " + string.Join(", ", stats.Select(stat => string.Create(CultureInfo.InvariantCulture, $"{stat.Key.Substring(2)} {stat.Value:R}"))) + ".");
|
||||
}
|
||||
if (args[0] == "product" && args.Length >= 4)
|
||||
{
|
||||
|
|
@ -178,51 +154,32 @@ public static class ShipAuthoringCommands
|
|||
var remove = !notOffered && count == 4 && args[3] == "--remove";
|
||||
var named = count >= 5 && args[3] == "--name" && (count == 5 || count == 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)
|
||||
var makerName = "";
|
||||
return Build(args[1], request =>
|
||||
{
|
||||
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
|
||||
var (makerKey, name) = ShippedFaction(args[2]);
|
||||
makerName = name;
|
||||
if (remove)
|
||||
{
|
||||
if (!request.Products.Any(product => product.Maker == makerKey.Value))
|
||||
throw new InvalidOperationException($"{request.Ship}: the package holds no product by that maker.");
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(args[4]))
|
||||
throw new InvalidOperationException("--name: a product needs a name.");
|
||||
request.Products.RemoveAll(product => product.Maker == makerKey.Value);
|
||||
if (!remove)
|
||||
request.Products.Add(new ShipAuthoringPush.ProductRow
|
||||
{
|
||||
Name = args[4],
|
||||
Description = count == 7 ? args[6] : null,
|
||||
Design = new CultRecordRef<CraftedItemData>(ShipModCatalog.HullKey(ship.Id)),
|
||||
Manufacturer = new CultRecordRef<Faction>(makerKey),
|
||||
// A hull stored with no roles (Zenith, so a station made --like it) decodes with a null list.
|
||||
Roles = (hull.Roles ?? new List<ItemRole>()).Select(role => new ProductRole { Role = role.Name }).ToList(),
|
||||
NotOffered = notOffered
|
||||
Maker = makerKey.Value, Name = args[4], Description = count == 7 ? args[6] : null, Offered = !notOffered
|
||||
});
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
Console.WriteLine($"{ship.Id}: {(remove ? "removed" : "wrote")} the product by {makerName}{(notOffered ? ", not offered" : "")}.");
|
||||
return 0;
|
||||
}, ship => $"{ship}: {(remove ? "removed" : "wrote")} the product by {makerName}{(notOffered ? ", not offered" : "")}.");
|
||||
}
|
||||
if (args[0] == "kind" && args.Length == 3)
|
||||
{
|
||||
// A thin builder over the push core: load through the cache the push loads from, derive the hull with its kind, judge
|
||||
// it by the one kind rule against the shipped catalog (read-only), and commit through Land, the push's compare-exchange
|
||||
// path, so a hull written since the load is refused as stale and the file stays as it was.
|
||||
using var cache = ShipAuthoringStore.Open(args[1], writable: true);
|
||||
var (hull, ship, _) = ShipAuthoringStore.Load(cache, args[1]);
|
||||
var derived = ShipAuthoringPush.Copy(hull);
|
||||
derived.Kind = new CultRecordRef<StationKindData>(StationKindData.KeyOf(args[2]));
|
||||
using (var catalog = AetherDb.Open().Cache)
|
||||
if (StationKinds.HullKindFault(catalog, derived) is { } fault) throw new InvalidOperationException($"{ship.Id}: {fault}");
|
||||
var key = ShipModCatalog.HullKey(ship.Id);
|
||||
if (!ShipAuthoringPush.Land(cache, new[] { new ShipAuthoringPush.Write(key, typeof(HullData), hull, derived) }))
|
||||
throw new InvalidOperationException($"{ship.Id}: the hull was written since it was loaded; nothing was changed.");
|
||||
cache.FlushAsync().Wait();
|
||||
Console.WriteLine($"{ship.Id}: kind {derived.Kind.Key.Value}.");
|
||||
return 0;
|
||||
// A builder over the push core: the core judges a changed kind by the one kind rule against the shipped catalog
|
||||
// and refuses it as '<id>: <fault>', and a hull written since the load is stale and left as it was.
|
||||
var kind = StationKindData.KeyOf(args[2]).Value;
|
||||
return Build(args[1], request => request.Hull.Kind = kind, ship => $"{ship}: kind {kind}.");
|
||||
}
|
||||
Console.Error.WriteLine(Usage);
|
||||
return 1;
|
||||
|
|
@ -234,6 +191,25 @@ public static class ShipAuthoringCommands
|
|||
}
|
||||
}
|
||||
|
||||
// price, stats, product and kind are request builders over the push core: each opens the package's request, sets the one
|
||||
// section it owns, and applies it. A refusal throws (stderr, exit 1, the file untouched); a record written since the open
|
||||
// is stale (exit 2); success prints the builder's own line.
|
||||
private static int Build(string path, Action<ShipAuthoringPush.Request> edit, Func<string, string> success)
|
||||
{
|
||||
ShipAuthoringPush.Request request;
|
||||
using (var cache = ShipAuthoringStore.Open(path)) request = ShipAuthoringPush.Opened(cache, path);
|
||||
edit(request);
|
||||
var result = ShipAuthoringPush.Run(path, request, apply: true);
|
||||
if (result.Outcome == "refused") throw new InvalidOperationException(result.Message);
|
||||
if (result.Outcome == "stale")
|
||||
{
|
||||
Console.Error.WriteLine($"{request.Ship}: the package was written while this ran; run it again.");
|
||||
return 2;
|
||||
}
|
||||
Console.WriteLine(success(request.Ship));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The judgment validate reports and push reports on its derived records: the package's records, and its GLB too once it
|
||||
// exists (node ids, mesh roles); a draft without one is judged on its records alone, and the label says which. A package
|
||||
// with no products and no station kind to judge has no bin and is never offered, so the shipped catalog is opened for none.
|
||||
|
|
@ -254,13 +230,14 @@ public static class ShipAuthoringCommands
|
|||
return judged;
|
||||
}
|
||||
|
||||
// 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)
|
||||
// A shipped faction by record key, name or short name, from GameData/Aetheria.cc opened read-only: exactly one, or refused.
|
||||
internal static (CultRecordKey Key, string Name) ShippedFaction(string text)
|
||||
{
|
||||
using var catalog = AetherDb.Open().Cache;
|
||||
var matches = catalog.GetAll<Faction>()
|
||||
.Where(faction => string.Equals(faction.Name, nameOrShortName, StringComparison.Ordinal) ||
|
||||
string.Equals(faction.ShortName, nameOrShortName, StringComparison.Ordinal)).ToArray();
|
||||
.Where(faction => string.Equals(faction.Name, text, StringComparison.Ordinal) ||
|
||||
string.Equals(faction.ShortName, text, StringComparison.Ordinal) ||
|
||||
string.Equals(catalog.TryGetHandle(faction).Value.Key.Value, text, StringComparison.Ordinal)).ToArray();
|
||||
if (matches.Length != 1)
|
||||
throw new InvalidOperationException($"<maker>: 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);
|
||||
|
|
|
|||
|
|
@ -18,24 +18,50 @@ public static class ShipAuthoringPush
|
|||
{
|
||||
// A request is open's output and is parsed strictly: an unknown key and a missing key are refused by name.
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
private sealed class Request
|
||||
internal sealed class Request
|
||||
{
|
||||
[JsonProperty("ship", Required = Required.DisallowNull)] public string Ship;
|
||||
// Checked against the stored HullType, never written.
|
||||
[JsonProperty("hullType")] public string HullType;
|
||||
[JsonProperty("versions", Required = Required.DisallowNull)] public Dictionary<string, string> Versions;
|
||||
[JsonProperty("layout")] public LayoutSection Layout;
|
||||
[JsonProperty("visual")] public VisualSection Visual;
|
||||
[JsonProperty("lines")] public List<LineRow> Lines;
|
||||
[JsonProperty("hull")] public HullSection Hull;
|
||||
[JsonProperty("products")] public List<ProductRow> Products;
|
||||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
private sealed class LayoutSection
|
||||
internal sealed class HullSection
|
||||
{
|
||||
[JsonProperty("name", Required = Required.DisallowNull)] public string Name;
|
||||
[JsonProperty("price", Required = Required.Always)] public int Price;
|
||||
[JsonProperty("mass", Required = Required.Always)] public float Mass;
|
||||
[JsonProperty("durability", Required = Required.Always)] public float Durability;
|
||||
[JsonProperty("armor", Required = Required.Always)] public float Armor;
|
||||
[JsonProperty("drag", Required = Required.Always)] public float Drag;
|
||||
[JsonProperty("topSpeed", Required = Required.AllowNull)] public float? TopSpeed;
|
||||
[JsonProperty("kind", Required = Required.AllowNull)] public string Kind;
|
||||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
internal sealed class ProductRow
|
||||
{
|
||||
[JsonProperty("maker", Required = Required.DisallowNull)] public string Maker;
|
||||
[JsonProperty("name", Required = Required.DisallowNull)] public string Name;
|
||||
[JsonProperty("description", Required = Required.AllowNull)] public string Description;
|
||||
[JsonProperty("offered", Required = Required.Always)] public bool Offered;
|
||||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
internal sealed class LayoutSection
|
||||
{
|
||||
[JsonProperty("grid", Required = Required.DisallowNull)] public string Grid;
|
||||
[JsonProperty("hardpoints", Required = Required.DisallowNull)] public List<HardpointRow> Hardpoints;
|
||||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
private sealed class HardpointRow
|
||||
internal sealed class HardpointRow
|
||||
{
|
||||
[JsonProperty("element", Required = Required.DisallowNull)] public string Element;
|
||||
[JsonProperty("mount", Required = Required.DisallowNull)] public string Mount;
|
||||
|
|
@ -48,14 +74,14 @@ public static class ShipAuthoringPush
|
|||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
private sealed class VisualSection
|
||||
internal sealed class VisualSection
|
||||
{
|
||||
[JsonProperty("model", Required = Required.DisallowNull)] public string Model;
|
||||
[JsonProperty("anchors", Required = Required.DisallowNull)] public List<AnchorRow> Anchors;
|
||||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
private sealed class AnchorRow
|
||||
internal sealed class AnchorRow
|
||||
{
|
||||
[JsonProperty("id", Required = Required.DisallowNull)] public string Id;
|
||||
[JsonProperty("role", Required = Required.DisallowNull)] public string Role;
|
||||
|
|
@ -65,7 +91,7 @@ public static class ShipAuthoringPush
|
|||
}
|
||||
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
private sealed class LineRow
|
||||
internal sealed class LineRow
|
||||
{
|
||||
[JsonProperty("element", Required = Required.DisallowNull)] public string Element;
|
||||
[JsonProperty("layer", Required = Required.AllowNull)] public string Layer;
|
||||
|
|
@ -96,64 +122,83 @@ public static class ShipAuthoringPush
|
|||
public static int Open(string path, TextWriter output)
|
||||
{
|
||||
using var cache = ShipAuthoringStore.Open(path);
|
||||
var (hull, ship, _) = ShipAuthoringStore.Load(cache, path);
|
||||
var request = new Dictionary<string, object>
|
||||
{
|
||||
["ship"] = ship.Id,
|
||||
["versions"] = Versions(cache, ship.Id),
|
||||
["layout"] = new Dictionary<string, object>
|
||||
{
|
||||
["grid"] = Footprint(hull.Shape),
|
||||
["hardpoints"] = (hull.Hardpoints ?? new List<HardpointData>()).Select(hardpoint => new Dictionary<string, object>
|
||||
{
|
||||
["element"] = hardpoint.Id ?? "",
|
||||
["mount"] = hardpoint.Transform,
|
||||
["kind"] = hardpoint.Type.ToString(),
|
||||
["cell"] = new[] { hardpoint.Position.x, hardpoint.Position.y },
|
||||
["footprint"] = Footprint(hardpoint.Shape),
|
||||
["rotation"] = (int)hardpoint.Rotation,
|
||||
["armor"] = hardpoint.Armor,
|
||||
["arc"] = hardpoint.FiringArc
|
||||
}).ToList()
|
||||
},
|
||||
["visual"] = new Dictionary<string, object>
|
||||
{
|
||||
["model"] = ship.ModelAsset,
|
||||
["anchors"] = (ship.Anchors ?? new List<ShipAnchor>()).Select(anchor => new Dictionary<string, object>
|
||||
{
|
||||
["id"] = anchor.Id,
|
||||
["role"] = anchor.Role,
|
||||
["node"] = anchor.ModelNodeId,
|
||||
["parent"] = anchor.ParentId,
|
||||
["order"] = anchor.Order
|
||||
}).ToList()
|
||||
},
|
||||
["lines"] = (ship.SchematicLines ?? new List<ShipPolyline>()).Select(line => new Dictionary<string, object>
|
||||
{
|
||||
["element"] = line.Id ?? "",
|
||||
["layer"] = line.Layer,
|
||||
["material"] = line.Material,
|
||||
["points"] = line.Points,
|
||||
["radii"] = line.Radii,
|
||||
["opacities"] = line.Opacities,
|
||||
["cyclic"] = line.Cyclic,
|
||||
["color"] = line.Color
|
||||
}).ToList()
|
||||
};
|
||||
output.WriteLine(JsonConvert.SerializeObject(request, Formatting.Indented));
|
||||
output.WriteLine(JsonConvert.SerializeObject(Opened(cache, path), Formatting.Indented));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The package's authored members as a typed request: open prints it, and the builders (stats, price, kind, product) edit
|
||||
// the one section they own and hand it to Run.
|
||||
internal static Request Opened(CultCache cache, string path)
|
||||
{
|
||||
var (hull, ship, products) = ShipAuthoringStore.Load(cache, path);
|
||||
return new Request
|
||||
{
|
||||
Ship = ship.Id,
|
||||
HullType = hull.HullType.ToString(),
|
||||
Versions = Versions(cache, ship.Id),
|
||||
Layout = new LayoutSection
|
||||
{
|
||||
Grid = Footprint(hull.Shape),
|
||||
Hardpoints = (hull.Hardpoints ?? new List<HardpointData>()).Select(hardpoint => new HardpointRow
|
||||
{
|
||||
Element = hardpoint.Id ?? "",
|
||||
Mount = hardpoint.Transform,
|
||||
Kind = hardpoint.Type.ToString(),
|
||||
Cell = new[] { hardpoint.Position.x, hardpoint.Position.y },
|
||||
Footprint = Footprint(hardpoint.Shape),
|
||||
Rotation = (int)hardpoint.Rotation,
|
||||
Armor = hardpoint.Armor,
|
||||
Arc = hardpoint.FiringArc
|
||||
}).ToList()
|
||||
},
|
||||
Visual = new VisualSection
|
||||
{
|
||||
Model = ship.ModelAsset,
|
||||
Anchors = (ship.Anchors ?? new List<ShipAnchor>()).Select(anchor => new AnchorRow
|
||||
{
|
||||
Id = anchor.Id, Role = anchor.Role, Node = anchor.ModelNodeId, Parent = anchor.ParentId, Order = anchor.Order
|
||||
}).ToList()
|
||||
},
|
||||
Lines = (ship.SchematicLines ?? new List<ShipPolyline>()).Select(line => new LineRow
|
||||
{
|
||||
Element = line.Id ?? "", Layer = line.Layer, Material = line.Material, Points = line.Points, Radii = line.Radii,
|
||||
Opacities = line.Opacities, Cyclic = line.Cyclic, Color = line.Color
|
||||
}).ToList(),
|
||||
Hull = new HullSection
|
||||
{
|
||||
Name = hull.Name, Price = hull.Price, Mass = hull.Mass, Durability = hull.Durability, Armor = hull.Armor,
|
||||
Drag = hull.Drag, TopSpeed = TopSpeed(hull), Kind = KindText(hull)
|
||||
},
|
||||
Products = products.OrderBy(product => product.Manufacturer.Key.Value, StringComparer.Ordinal).Select(product => new ProductRow
|
||||
{
|
||||
Maker = product.Manufacturer.Key.Value, Name = product.Name, Description = product.Description, Offered = !product.NotOffered
|
||||
}).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
// The hull, the ship and every product record the package holds, each by the store's version token.
|
||||
private static Dictionary<string, string> Versions(CultCache cache, string shipId) =>
|
||||
new[] { ShipModCatalog.HullKey(shipId), ShipModCatalog.AuthoringKey(shipId) }
|
||||
.Concat(cache.GetAll<FactionProductData>().Select(product => cache.TryGetHandle(product).Value.Key))
|
||||
.ToDictionary(key => key.Value, key => cache.GetStored(key).StoredAt, StringComparer.Ordinal);
|
||||
|
||||
// The result of a push: what the print shows and the builders read.
|
||||
internal sealed class Result
|
||||
{
|
||||
public string Outcome;
|
||||
public int Code;
|
||||
public string Message;
|
||||
public List<string> Lines = new List<string>();
|
||||
public List<string> Changed = new List<string>();
|
||||
public List<string> Stale = new List<string>();
|
||||
public string Verdict;
|
||||
public Dictionary<string, string> Versions;
|
||||
}
|
||||
|
||||
// Reads a request from stdin and prints what it would change; with apply, writes it. Exit 0 dry run or applied,
|
||||
// 1 refused (the file is untouched), 2 stale (a record was written since the request's open; nothing is written).
|
||||
public static int Push(string path, TextReader requestText, bool apply, TextWriter output)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var changed = new List<string>();
|
||||
Request request;
|
||||
try
|
||||
{
|
||||
|
|
@ -161,6 +206,21 @@ public static class ShipAuthoringPush
|
|||
}
|
||||
catch (JsonException error) { return Refused(output, "request: " + error.Message); }
|
||||
if (request == null) return Refused(output, "request: the request is empty.");
|
||||
var result = Run(path, request, apply);
|
||||
if (result.Outcome == "refused") return Refused(output, result.Message);
|
||||
foreach (var line in result.Lines) output.WriteLine(line);
|
||||
output.WriteLine(JsonConvert.SerializeObject(new Dictionary<string, object>
|
||||
{
|
||||
["outcome"] = result.Outcome, ["changed"] = result.Changed, ["stale"] = result.Stale, ["verdict"] = result.Verdict, ["versions"] = result.Versions
|
||||
}));
|
||||
return result.Code;
|
||||
}
|
||||
|
||||
// The one core: push and the builders both come here. A refusal leaves the file untouched (Code 1, Message); a stale
|
||||
// record writes nothing (Code 2).
|
||||
internal static Result Run(string path, Request request, bool apply)
|
||||
{
|
||||
var result = new Result();
|
||||
try
|
||||
{
|
||||
using var cache = ShipAuthoringStore.Open(path, writable: apply);
|
||||
|
|
@ -169,47 +229,65 @@ public static class ShipAuthoringPush
|
|||
var shipKey = ShipModCatalog.AuthoringKey(ship.Id);
|
||||
if (!string.Equals(request.Ship, ship.Id, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"request: ship is not {ship.Id}; the request was opened from another package.");
|
||||
if (request.HullType != null && !string.Equals(request.HullType, hull.HullType.ToString(), StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"request: hullType is {request.HullType}; this package's hull is a {hull.HullType}.");
|
||||
|
||||
var lines = result.Lines;
|
||||
var newHull = Copy(hull);
|
||||
var newShip = Copy(ship);
|
||||
if (request.Layout != null) DeriveLayout(request.Layout, hull, newHull, hullKey.Value, lines);
|
||||
if (request.Visual != null) DeriveVisual(request.Visual, ship, newShip, shipKey.Value, lines);
|
||||
if (request.Lines != null) DeriveLines(request.Lines, ship, newShip, shipKey.Value, lines);
|
||||
if (request.Hull != null) DeriveHull(request.Hull, hull, newHull, hullKey.Value, ship.Id, lines);
|
||||
var productWrites = request.Products != null ? DeriveProducts(request.Products, products, newHull, ship.Id, lines) : new List<Write>();
|
||||
|
||||
var writes = new List<Write>();
|
||||
if (!Pack(newHull).AsSpan().SequenceEqual(Pack(hull))) writes.Add(new Write(hullKey, typeof(HullData), hull, newHull));
|
||||
if (!Pack(newShip).AsSpan().SequenceEqual(Pack(ship))) writes.Add(new Write(shipKey, typeof(ShipAuthoring), ship, newShip));
|
||||
writes.AddRange(productWrites);
|
||||
|
||||
var productPrefix = "mod-product:" + ship.Id + ":";
|
||||
foreach (var held in request.Versions.Keys)
|
||||
if (held != hullKey.Value && held != shipKey.Value)
|
||||
throw new InvalidOperationException($"request: versions names {held}, which this push does not write; it may name {hullKey.Value} and {shipKey.Value}.");
|
||||
if (held != hullKey.Value && held != shipKey.Value && !held.StartsWith(productPrefix, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"request: versions names {held}, which this push does not write; it may name {hullKey.Value}, {shipKey.Value} and {productPrefix}<maker>.");
|
||||
foreach (var write in writes)
|
||||
if (!request.Versions.ContainsKey(write.Key.Value))
|
||||
if ((write.Key.Equals(hullKey) || write.Key.Equals(shipKey)) && !request.Versions.ContainsKey(write.Key.Value))
|
||||
throw new InvalidOperationException($"request: versions has no entry for {write.Key.Value}, which this push writes.");
|
||||
changed.AddRange(writes.Select(write => write.Key.Value));
|
||||
result.Changed.AddRange(writes.Select(write => write.Key.Value));
|
||||
|
||||
var verdict = Verdict(path, newHull, newShip, products);
|
||||
foreach (var line in lines) output.WriteLine(line);
|
||||
// The products Judge sees: the stored ones with each product write applied.
|
||||
var written = productWrites.ToDictionary(write => write.Key.Value, StringComparer.Ordinal);
|
||||
var judged = products.Where(product => !written.ContainsKey(ShipModCatalog.ProductKey(ship.Id, product.Manufacturer.Key).Value))
|
||||
.Concat(productWrites.Where(write => write.Derived != null).Select(write => (FactionProductData)write.Derived)).ToArray();
|
||||
result.Verdict = Verdict(path, newHull, newShip, judged);
|
||||
|
||||
var stale = writes.Where(write => !string.Equals(request.Versions[write.Key.Value], cache.GetStored(write.Key).StoredAt, StringComparison.Ordinal))
|
||||
.Select(write => write.Key.Value).ToList();
|
||||
// A record the request carries a version for is expected as that instance; one it carries none for (a product it
|
||||
// did not open) is expected absent.
|
||||
bool Stale(Write write) => request.Versions.TryGetValue(write.Key.Value, out var version)
|
||||
? write.Held == null || !string.Equals(version, cache.GetStored(write.Key).StoredAt, StringComparison.Ordinal)
|
||||
: write.Held != null;
|
||||
var stale = writes.Where(Stale).Select(write => write.Key.Value).ToList();
|
||||
if (stale.Count == 0 && apply && writes.Count > 0)
|
||||
{
|
||||
var landed = Land(cache, writes);
|
||||
if (landed) cache.FlushAsync().Wait();
|
||||
else stale = writes.Select(write => write.Key.Value).ToList();
|
||||
}
|
||||
if (stale.Count > 0) return Outcome(output, "stale", changed, stale, verdict, Versions(cache, ship.Id), 2);
|
||||
return Outcome(output, apply ? "applied" : "dry-run", changed, stale, verdict, Versions(cache, ship.Id), 0);
|
||||
result.Stale = stale;
|
||||
result.Versions = Versions(cache, ship.Id);
|
||||
result.Code = stale.Count > 0 ? 2 : 0;
|
||||
result.Outcome = stale.Count > 0 ? "stale" : apply ? "applied" : "dry-run";
|
||||
return result;
|
||||
}
|
||||
catch (InvalidOperationException error) { return Refused(output, error.Message); }
|
||||
catch (InvalidOperationException error) { return new Result { Outcome = "refused", Code = 1, Message = error.Message }; }
|
||||
}
|
||||
|
||||
// A record to write: the instance the cache holds, and the copy derived from it.
|
||||
// A record to write: the instance the cache holds (null: the key is absent, an add) and the copy derived from it
|
||||
// (null: a removal).
|
||||
internal readonly record struct Write(CultRecordKey Key, Type Type, object Held, object Derived);
|
||||
|
||||
// One commit, every record expected to still be the instance it was loaded as: a write that lands between the load and
|
||||
// this commit replaces that instance and is refused here (false), never overwritten.
|
||||
// One commit, every record expected to still be the instance it was loaded as (or absent): a write that lands between the
|
||||
// load and this commit replaces that instance and is refused here (false), never overwritten.
|
||||
internal static bool Land(CultCache cache, IReadOnlyList<Write> writes)
|
||||
{
|
||||
try
|
||||
|
|
@ -219,7 +297,8 @@ public static class ShipAuthoringPush
|
|||
foreach (var write in writes)
|
||||
{
|
||||
batch.Expect(write.Key, write.Held);
|
||||
batch.Upsert(write.Type, write.Derived, write.Key);
|
||||
if (write.Derived == null) batch.Remove(write.Key);
|
||||
else batch.Upsert(write.Type, write.Derived, write.Key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -234,22 +313,125 @@ public static class ShipAuthoringPush
|
|||
catch (Exception error) when (error is InvalidOperationException or JsonException) { return "refused: " + error.Message; }
|
||||
}
|
||||
|
||||
private static int Outcome(TextWriter output, string outcome, List<string> changed, List<string> stale, string verdict,
|
||||
Dictionary<string, string> versions, int code)
|
||||
{
|
||||
output.WriteLine(JsonConvert.SerializeObject(new Dictionary<string, object>
|
||||
{
|
||||
["outcome"] = outcome, ["changed"] = changed, ["stale"] = stale, ["verdict"] = verdict, ["versions"] = versions
|
||||
}));
|
||||
return code;
|
||||
}
|
||||
|
||||
private static int Refused(TextWriter output, string message)
|
||||
{
|
||||
output.WriteLine(JsonConvert.SerializeObject(new Dictionary<string, object> { ["outcome"] = "refused", ["message"] = message }));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- hull: name, price, stats, top speed, station kind ------------------------------------------------------------
|
||||
|
||||
// The one VelocityLimit's top speed when the hull has exactly one with a fixed speed (Min equal to Max), else null.
|
||||
private static float? TopSpeed(HullData hull)
|
||||
{
|
||||
var limits = (hull.Behaviors ?? new List<BehaviorData>()).OfType<VelocityLimitData>().ToArray();
|
||||
return limits.Length == 1 && limits[0].TopSpeed.Min == limits[0].TopSpeed.Max ? limits[0].TopSpeed.Max : null;
|
||||
}
|
||||
|
||||
private static string KindText(HullData hull) => hull.Kind.IsSet() ? hull.Kind.Key.Value : null;
|
||||
|
||||
private static void DeriveHull(HullSection section, HullData held, HullData derived, string key, string shipId, List<string> lines)
|
||||
{
|
||||
if (section.Price < 0) throw new InvalidOperationException("hull: price must be a whole number of at least 0.");
|
||||
foreach (var (field, value) in new[] { ("mass", section.Mass), ("durability", section.Durability), ("armor", section.Armor), ("drag", section.Drag) })
|
||||
if (!(value >= 0) || float.IsInfinity(value)) throw new InvalidOperationException($"hull: {field} must be finite and at least 0.");
|
||||
derived.Name = section.Name;
|
||||
derived.Price = section.Price;
|
||||
derived.Mass = section.Mass;
|
||||
derived.Durability = section.Durability;
|
||||
derived.Armor = section.Armor;
|
||||
derived.Drag = section.Drag;
|
||||
if (section.TopSpeed is { } speed)
|
||||
{
|
||||
if (!float.IsFinite(speed) || speed < 0) throw new InvalidOperationException("hull: topSpeed must be null, or finite and at least 0.");
|
||||
var limits = (derived.Behaviors ??= new List<BehaviorData>()).OfType<VelocityLimitData>().ToArray();
|
||||
if (limits.Length > 1) throw new InvalidOperationException($"{shipId}: --top-speed needs at most one VelocityLimit on the hull; it has {limits.Length}.");
|
||||
// A hull made without --like has none, and this is its only way to get one: validate refuses a ship without a top speed.
|
||||
if (limits.Length == 0)
|
||||
{
|
||||
limits = new[] { new VelocityLimitData() };
|
||||
derived.Behaviors.Add(limits[0]);
|
||||
}
|
||||
// A fixed top speed, as every shipped hull authors one (Min equal to Max); its terms are kept.
|
||||
limits[0].TopSpeed.Min = limits[0].TopSpeed.Max = speed;
|
||||
}
|
||||
derived.Kind = string.IsNullOrEmpty(section.Kind) ? default : new CultRecordRef<StationKindData>(new CultRecordKey(section.Kind));
|
||||
// Only a changed kind is judged here, so a kindless station draft still takes stats and price; the verdict judges the package.
|
||||
if (KindText(derived) != KindText(held))
|
||||
using (var catalog = AetherDb.Open().Cache)
|
||||
if (StationKinds.HullKindFault(catalog, derived) is { } fault) throw new InvalidOperationException($"{shipId}: {fault}");
|
||||
FlatDiff(lines, key, HullFields(held), HullFields(derived));
|
||||
}
|
||||
|
||||
private static (string Field, string Value)[] HullFields(HullData hull) => new[]
|
||||
{
|
||||
("name", hull.Name), ("price", Text(hull.Price)), ("mass", Text(hull.Mass)), ("durability", Text(hull.Durability)),
|
||||
("armor", Text(hull.Armor)), ("drag", Text(hull.Drag)), ("topSpeed", TopSpeed(hull) is { } speed ? Text(speed) : null), ("kind", KindText(hull))
|
||||
};
|
||||
|
||||
// ---- products: one FactionProductData per maker ------------------------------------------------------------------
|
||||
|
||||
private static List<Write> DeriveProducts(List<ProductRow> request, FactionProductData[] stored, HullData hull, string shipId, List<string> lines)
|
||||
{
|
||||
var byMaker = stored.ToDictionary(product => product.Manufacturer.Key.Value, StringComparer.Ordinal);
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var writes = new List<Write>();
|
||||
foreach (var row in request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(row.Name)) throw new InvalidOperationException($"products: {row.Maker}: a product needs a name.");
|
||||
// A maker that is a stored product's own key names it; any other is a shipped faction by key, name or short name.
|
||||
FactionProductData held;
|
||||
CultRecordKey maker;
|
||||
if (byMaker.TryGetValue(row.Maker, out held)) maker = held.Manufacturer.Key;
|
||||
else
|
||||
{
|
||||
maker = ShipAuthoringCommands.ShippedFaction(row.Maker).Key;
|
||||
byMaker.TryGetValue(maker.Value, out held);
|
||||
}
|
||||
if (!seen.Add(maker.Value)) throw new InvalidOperationException($"products: maker {row.Maker} names {maker.Value}, which another row names too.");
|
||||
var key = ShipModCatalog.ProductKey(shipId, maker);
|
||||
var derived = held != null ? Copy(held) : new FactionProductData
|
||||
{
|
||||
Design = new CultRecordRef<CraftedItemData>(ShipModCatalog.HullKey(shipId)),
|
||||
Manufacturer = new CultRecordRef<Faction>(maker),
|
||||
// A hull stored with no roles (Zenith, so a station made --like it) decodes with a null list.
|
||||
Roles = (hull.Roles ?? new List<ItemRole>()).Select(role => new ProductRole { Role = role.Name }).ToList()
|
||||
};
|
||||
derived.Name = row.Name;
|
||||
derived.Description = row.Description;
|
||||
derived.NotOffered = !row.Offered;
|
||||
if (held == null)
|
||||
{
|
||||
lines.Add($"{key.Value} added");
|
||||
writes.Add(new Write(key, typeof(FactionProductData), null, derived));
|
||||
}
|
||||
else if (!Pack(derived).AsSpan().SequenceEqual(Pack(held)))
|
||||
{
|
||||
FlatDiff(lines, key.Value, ProductFields(held), ProductFields(derived));
|
||||
writes.Add(new Write(key, typeof(FactionProductData), held, derived));
|
||||
}
|
||||
}
|
||||
foreach (var gone in stored.Where(product => !seen.Contains(product.Manufacturer.Key.Value)))
|
||||
{
|
||||
var key = ShipModCatalog.ProductKey(shipId, gone.Manufacturer.Key);
|
||||
lines.Add($"{key.Value} removed");
|
||||
writes.Add(new Write(key, typeof(FactionProductData), gone, null));
|
||||
}
|
||||
return writes.OrderBy(write => write.Key.Value, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
private static (string Field, string Value)[] ProductFields(FactionProductData product) => new[]
|
||||
{
|
||||
("name", product.Name), ("description", product.Description), ("offered", product.NotOffered ? "false" : "true")
|
||||
};
|
||||
|
||||
private static void FlatDiff(List<string> lines, string key, (string Field, string Value)[] before, (string Field, string Value)[] after)
|
||||
{
|
||||
for (var i = 0; i < before.Length; i++)
|
||||
if (!string.Equals(before[i].Value, after[i].Value, StringComparison.Ordinal))
|
||||
lines.Add($"{key} {before[i].Field}: {before[i].Value ?? "null"} -> {after[i].Value ?? "null"}");
|
||||
}
|
||||
|
||||
// ---- layout: HullData.Shape and HullData.Hardpoints --------------------------------------------------------------
|
||||
|
||||
private static void DeriveLayout(LayoutSection layout, HullData held, HullData derived, string key, List<string> lines)
|
||||
|
|
|
|||
Loading…
Reference in a new issue