Ship S1 fixes: refuse the retired embedded hull, one body per hull, closed validator gaps
Load reads the raw ship authoring payload and refuses a non-nil retired key 1 (the pre-S1 embedded hull) naming the old shape, so a stale hull is no longer silently ignored; ship_cc.py refuses the same file on read and therefore on every save. A hull naming both a Unity prefab and a visual is refused by one predicate (ShipAuthoringStore.RequireOneBody), called by Validate and by Compose over every hull in the derived catalog, shipped ones included; a whitespace-only Prefab is unset. This replaces the mod-ship-only "cannot name a Unity prefab" check. The validator also refuses non-finite or negative hardpoint Armor and FiringArc, an undefined HardpointType or ItemRotation, and an anchor Role outside the eight the schema documents. Load wraps MessagePack decode failures with the file path. Python replace_layout refuses non-boolean layout and hardpoint-footprint cells. Tests: exact Visual key comparison, HullData.Visual at key 32, a save refreshing stored_at, plus one case per new refusal. HullData.Visual is now [Inspectable] like Prefab (Unity editor only; not compiled here). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d1648800ab
commit
f470c1b775
9 changed files with 316 additions and 10 deletions
|
|
@ -532,7 +532,7 @@ public class HullData : EquippableItemData
|
|||
|
||||
// The hull's visual: a ShipAuthoring record holding its model package, or unset for a Unity-prefab hull. A hull
|
||||
// names exactly one of Prefab and Visual. Keys 30 and 31 are EquippableItemData's, so 32 is the next free key.
|
||||
[JsonProperty("visual"), Key(32)]
|
||||
[Inspectable, JsonProperty("visual"), Key(32)]
|
||||
public CultRecordRef<ShipAuthoring> Visual;
|
||||
|
||||
[IgnoreMember]
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
|
|
@ -49,6 +50,12 @@ public sealed class ShipPolyline
|
|||
|
||||
public static class ShipAuthoringStore
|
||||
{
|
||||
// ShipAnchor.Role's vocabulary.
|
||||
private static readonly HashSet<string> Roles = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-muzzle", "radiator-mesh", "articulation"
|
||||
};
|
||||
|
||||
public static CultCache Open(string path, bool writable = false)
|
||||
{
|
||||
var cache = new CultCache();
|
||||
|
|
@ -74,6 +81,49 @@ 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)
|
||||
{
|
||||
RefuseLegacyEmbeddedHull(path);
|
||||
try { return LoadRecords(path); }
|
||||
catch (MessagePackSerializationException error)
|
||||
{
|
||||
throw new InvalidOperationException($"{path}: a record does not decode as its schema: {error.Message}", error);
|
||||
}
|
||||
}
|
||||
|
||||
// Key 1 of ShipAuthoring held the whole hull before S1. The type no longer has that member, so a deserialized record
|
||||
// shows nothing of it, and a file that still carries one would load as a ship silently ignoring its old hull. The
|
||||
// raw payload is the only place the old shape is visible.
|
||||
private static void RefuseLegacyEmbeddedHull(string path)
|
||||
{
|
||||
if (!File.Exists(path)) return;
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
if (bytes.Length == 0) return;
|
||||
CultPersistedStoreSnapshot snapshot;
|
||||
try { snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes); }
|
||||
catch (MessagePackSerializationException error)
|
||||
{
|
||||
throw new InvalidOperationException($"{path}: not a readable ship file: {error.Message}", error);
|
||||
}
|
||||
var schema = typeof(ShipAuthoring).GetCustomAttribute<CultDocumentAttribute>().SchemaName;
|
||||
foreach (var record in snapshot.Records)
|
||||
{
|
||||
if (snapshot.SchemaCatalog.FirstOrDefault(entry => entry.SchemaId == record.SchemaId)?.SchemaName != schema) continue;
|
||||
var reader = new MessagePackReader(record.Payload);
|
||||
if (reader.NextMessagePackType != MessagePackType.Array) continue;
|
||||
var slots = reader.ReadArrayHeader();
|
||||
for (var slot = 0; slot < slots; slot++)
|
||||
{
|
||||
if (slot == RetiredHullKey && !reader.TryReadNil())
|
||||
throw new InvalidOperationException($"{path}: {record.Key}: legacy embedded hull at retired key {RetiredHullKey} of the ship authoring record. " +
|
||||
$"Migrate it: write the hull as its own hull record at mod-hull:<id> naming the visual, and rewrite the ship authoring record without key {RetiredHullKey}.");
|
||||
if (slot != RetiredHullKey) reader.Skip();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const int RetiredHullKey = 1;
|
||||
|
||||
private static (HullData Hull, ShipAuthoring Visual) LoadRecords(string path)
|
||||
{
|
||||
using var cache = Open(path);
|
||||
var hulls = cache.GetAll<HullData>().ToArray();
|
||||
|
|
@ -96,6 +146,15 @@ public static class ShipAuthoringStore
|
|||
return (hull, visual);
|
||||
}
|
||||
|
||||
// A hull names one body: a Unity prefab (shipped hulls) or a ShipAuthoring record (mod ships), never both, so no
|
||||
// consumer needs a precedence rule. A whitespace-only Prefab is unset. Every path that validates or composes hulls
|
||||
// calls this.
|
||||
public static void RequireOneBody(HullData hull, string label)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(hull.Prefab) && hull.Visual.IsSet())
|
||||
throw new InvalidOperationException($"{label}: a hull names one body, but this one names both a Unity prefab and a visual record.");
|
||||
}
|
||||
|
||||
// The one semantic check every path shares: the hull and its visual, judged together.
|
||||
public static void Validate(HullData hull, ShipAuthoring ship)
|
||||
{
|
||||
|
|
@ -108,9 +167,7 @@ public static class ShipAuthoringStore
|
|||
if (string.IsNullOrWhiteSpace(hull.Name)) throw new InvalidOperationException($"{ship.Id}: hull name is required.");
|
||||
if (hull.Shape?.Cells == null || !hull.Shape.Cells.Cast<bool>().Any(occupied => occupied))
|
||||
throw new InvalidOperationException($"{ship.Id}: schematic must contain at least one cell.");
|
||||
// A hull names exactly one visual: a Unity prefab (shipped hulls) or a ShipAuthoring record (mod ships).
|
||||
if (!string.IsNullOrEmpty(hull.Prefab))
|
||||
throw new InvalidOperationException($"{ship.Id}: a mod ship cannot name a Unity prefab.");
|
||||
RequireOneBody(hull, ship.Id);
|
||||
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) ||
|
||||
|
|
@ -129,6 +186,9 @@ public static class ShipAuthoringStore
|
|||
if (!nodeIds.Add(anchor.ModelNodeId))
|
||||
throw new InvalidOperationException($"{ship.Id}: model node {anchor.ModelNodeId} is claimed by more than one anchor.");
|
||||
}
|
||||
foreach (var anchor in anchors)
|
||||
if (!Roles.Contains(anchor.Role))
|
||||
throw new InvalidOperationException($"{ship.Id}: anchor {anchor.Id} has unknown role '{anchor.Role}'.");
|
||||
foreach (var role in new[] { "map-icon", "hull-collider", "shield", "tractor" })
|
||||
if (anchors.Count(anchor => anchor.Role == role) != 1)
|
||||
throw new InvalidOperationException($"{ship.Id}: exactly one {role} anchor is required.");
|
||||
|
|
@ -140,6 +200,12 @@ public static class ShipAuthoringStore
|
|||
if (hardpoint == null || string.IsNullOrWhiteSpace(hardpoint.Transform) ||
|
||||
!mounts.Add(hardpoint.Transform))
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint IDs must be present and unique.");
|
||||
if (!Enum.IsDefined(typeof(HardpointType), hardpoint.Type))
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has an unknown type {(int)hardpoint.Type}.");
|
||||
if (!Enum.IsDefined(typeof(ItemRotation), hardpoint.Rotation))
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has an unknown rotation {(int)hardpoint.Rotation}.");
|
||||
if (!float.IsFinite(hardpoint.Armor) || hardpoint.Armor < 0 || !float.IsFinite(hardpoint.FiringArc) || hardpoint.FiringArc < 0)
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} armor and firing arc must be finite and not negative.");
|
||||
if (hardpoint.Shape?.Cells == null || !hardpoint.Shape.Cells.Cast<bool>().Any(occupied => occupied))
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has no cells.");
|
||||
for (var cellX = 0; cellX < hardpoint.Shape.Width; cellX++)
|
||||
|
|
|
|||
|
|
@ -70,6 +70,9 @@ public static class ShipModCatalog
|
|||
// Verbatim: the mod store's own two records, under the keys it already holds them at.
|
||||
ShipAuthoringStore.Write(cache, hull, ship);
|
||||
}
|
||||
// Shipped hulls too: the derived catalog must not hold a hull that names two bodies.
|
||||
foreach (var hull in cache.GetAll<HullData>())
|
||||
ShipAuthoringStore.RequireOneBody(hull, hull.Name);
|
||||
cache.FlushAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
if (File.Exists(output)) File.Replace(temporary, output, null);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using Xunit;
|
||||
|
|
@ -83,7 +86,12 @@ public sealed class ShipAuthoringTests
|
|||
{
|
||||
var ship = Fixture();
|
||||
ship.Hull.Prefab = "Djinni";
|
||||
Assert.Contains("cannot name a Unity prefab", Assert.Throws<InvalidOperationException>(ship.Validate).Message);
|
||||
Assert.Contains("names both a Unity prefab and a visual record", Assert.Throws<InvalidOperationException>(ship.Validate).Message);
|
||||
|
||||
// A whitespace-only prefab is unset.
|
||||
ship = Fixture();
|
||||
ship.Hull.Prefab = " \t";
|
||||
ship.Validate();
|
||||
|
||||
ship = Fixture();
|
||||
ship.Hull.Visual = default;
|
||||
|
|
@ -93,9 +101,93 @@ public sealed class ShipAuthoringTests
|
|||
ship.Hull.Visual = new CultRecordRef<ShipAuthoring>(ShipModCatalog.AuthoringKey("mod.other"));
|
||||
Assert.Contains("the hull must name its visual record mod-ship:mod.skiff", Assert.Throws<InvalidOperationException>(ship.Validate).Message);
|
||||
|
||||
// The key is compared exactly: a differently-cased key is another record.
|
||||
ship = Fixture();
|
||||
ship.Hull.Visual = new CultRecordRef<ShipAuthoring>(new CultRecordKey("MOD-SHIP:mod.skiff"));
|
||||
Assert.Contains("the hull must name its visual record mod-ship:mod.skiff", Assert.Throws<InvalidOperationException>(ship.Validate).Message);
|
||||
|
||||
Fixture().Validate();
|
||||
}
|
||||
|
||||
// A hull with both a prefab and a visual is refused wherever hulls are validated or composed.
|
||||
// ShipModCatalogTests.ComposeRefusesAShippedHullThatNamesTwoBodies covers Compose.
|
||||
[Fact]
|
||||
public void RequireOneBodyRefusesBothAndAcceptsEitherAlone()
|
||||
{
|
||||
var hull = Fixture().Hull;
|
||||
ShipAuthoringStore.RequireOneBody(hull, "skiff");
|
||||
hull.Prefab = "Djinni";
|
||||
Assert.Contains("skiff: a hull names one body", Assert.Throws<InvalidOperationException>(() => ShipAuthoringStore.RequireOneBody(hull, "skiff")).Message);
|
||||
hull.Visual = default;
|
||||
ShipAuthoringStore.RequireOneBody(hull, "skiff");
|
||||
}
|
||||
|
||||
// The ship authoring record held the whole hull at key 1 before S1.
|
||||
[Fact]
|
||||
public async Task LoadRefusesAShipAuthoringRecordThatStillCarriesTheRetiredEmbeddedHull()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
var path = Path.Combine(directory.Path, "legacy.cc");
|
||||
using (var cache = ShipAuthoringStore.Open(path, writable: true))
|
||||
{
|
||||
ShipAuthoringStore.Write(cache, Fixture().Hull, Fixture().Visual);
|
||||
await cache.FlushAsync();
|
||||
}
|
||||
RewritePayload(path, "aetheria.ship_authoring", slots => { slots[1] = new object[] { "Skiff" }; });
|
||||
foreach (var load in new Action[] { () => ShipAuthoringStore.Load(path), () => ShipAuthoringStore.Read(path) })
|
||||
{
|
||||
var message = Assert.Throws<InvalidOperationException>(load).Message;
|
||||
Assert.Contains("legacy embedded hull at retired key 1", message);
|
||||
Assert.Contains(path, message);
|
||||
}
|
||||
|
||||
// An old file has no separate hull record at all; it is named for what it is, not for a missing hull.
|
||||
var oldShape = Path.Combine(directory.Path, "old.cc");
|
||||
using (var cache = ShipAuthoringStore.Open(oldShape, writable: true))
|
||||
{
|
||||
cache.UpsertAsync(typeof(ShipAuthoring), Fixture().Visual, ShipModCatalog.AuthoringKey("mod.skiff")).GetAwaiter().GetResult();
|
||||
await cache.FlushAsync();
|
||||
}
|
||||
RewritePayload(oldShape, "aetheria.ship_authoring", slots => { slots[1] = new object[] { "Skiff" }; });
|
||||
var oldMessage = Assert.Throws<InvalidOperationException>(() => ShipAuthoringStore.Load(oldShape)).Message;
|
||||
Assert.Contains("legacy embedded hull", oldMessage);
|
||||
Assert.DoesNotContain("exactly one hull record", oldMessage);
|
||||
|
||||
// A nil in the retired slot is the shape every current file has.
|
||||
RewritePayload(path, "aetheria.ship_authoring", slots => { slots[1] = null; });
|
||||
ShipAuthoringStore.Load(path);
|
||||
}
|
||||
|
||||
// The layout editor's Python once accepted any msgpack value in a cell; C# then failed with a bare serializer exception.
|
||||
[Fact]
|
||||
public async Task LoadNamesTheFileWhoseRecordDoesNotDecode()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
var path = Path.Combine(directory.Path, "cells.cc");
|
||||
using (var cache = ShipAuthoringStore.Open(path, writable: true))
|
||||
{
|
||||
ShipAuthoringStore.Write(cache, Fixture().Hull, Fixture().Visual);
|
||||
await cache.FlushAsync();
|
||||
}
|
||||
// ItemData.Shape is key 5: [[width, height, cells]].
|
||||
RewritePayload(path, "aetheria.hulldata", slots => ((object[])((object[])slots[5])[0])[2] = new object[] { 5, false, true, false });
|
||||
var error = Assert.Throws<InvalidOperationException>(() => ShipAuthoringStore.Load(path));
|
||||
Assert.Contains(path, error.Message);
|
||||
Assert.IsAssignableFrom<MessagePackSerializationException>(error.InnerException);
|
||||
}
|
||||
|
||||
// Decodes one record's payload of the named schema to its slot array, lets the edit change it, and stores it again.
|
||||
private static void RewritePayload(string path, string schemaName, Action<object[]> edit)
|
||||
{
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path));
|
||||
var schemaId = snapshot.SchemaCatalog.Single(entry => entry.SchemaName == schemaName).SchemaId;
|
||||
var record = snapshot.Records.Single(candidate => candidate.SchemaId == schemaId);
|
||||
var slots = MessagePackSerializer.Deserialize<object[]>(record.Payload);
|
||||
edit(slots);
|
||||
record.Payload = MessagePackSerializer.Serialize(slots);
|
||||
File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadRefusesAFileWhoseRecordsAreNotOneHullAndOneVisualAtTheirKeys()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -65,6 +65,26 @@ public sealed class ShipModCatalogTests : IDisposable
|
|||
Assert.Equal("mod.skiff", visual.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComposeRefusesAShippedHullThatNamesTwoBodies()
|
||||
{
|
||||
WritePackage("mod.skiff");
|
||||
using (var cache = AetheriaStores.Open(Shipped, catalogWritable: true))
|
||||
{
|
||||
cache.Upsert(new HullData
|
||||
{
|
||||
Name = "Chimera",
|
||||
Shape = ShipAuthoringTests.Fixture().Hull.Shape,
|
||||
Prefab = "Djinni",
|
||||
Visual = new CultRecordRef<ShipAuthoring>(ShipModCatalog.AuthoringKey("mod.skiff"))
|
||||
});
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
Assert.Contains("Chimera: a hull names one body",
|
||||
Assert.Throws<InvalidOperationException>(() => ShipModCatalog.Compose(Shipped, Derived, Mods)).Message);
|
||||
Assert.False(File.Exists(Derived));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComposeCopiesTheModStoresRecordsUnchangedAndTheHullNamesItsVisualByRef()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -31,11 +31,22 @@ public sealed class ShipSchemaPinTests
|
|||
{
|
||||
Assert.Equal(typeof(ShipAuthoring).GetCustomAttribute<CultDocumentAttribute>().SchemaName, Text("SCHEMA"));
|
||||
Assert.Equal(typeof(HullData).GetCustomAttribute<CultDocumentAttribute>().SchemaName, Text("HULL_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),
|
||||
member => member.GetCustomAttribute<KeyAttribute>()?.IntKey == 1);
|
||||
}
|
||||
|
||||
// HullData.Visual is the one binding between a hull and its visual; its slot is the wire contract.
|
||||
[Fact]
|
||||
public void HullVisualIsKey32()
|
||||
{
|
||||
Assert.Equal(32, KeyOf(typeof(HullData), nameof(HullData.Visual)));
|
||||
var taken = typeof(HullData).GetMembers(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Select(member => member.GetCustomAttribute<KeyAttribute>()?.IntKey).Where(key => key != null).ToArray();
|
||||
Assert.Equal(taken.Length, taken.Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PythonHardpointMembersAreHardpointDataMembersAtTheirOwnPositions()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -27,6 +27,17 @@ public sealed class ShipValidationTests
|
|||
Assert.Contains(Cases[name].Message, error.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HardpointsAtTheEdgesOfTheirRangesAreValid()
|
||||
{
|
||||
var ship = ShipAuthoringTests.Fixture();
|
||||
ship.Hull.Hardpoints[0].Armor = 5;
|
||||
ship.Hull.Hardpoints[0].FiringArc = 360;
|
||||
ship.Hull.Hardpoints[0].Type = HardpointType.AetherDrive;
|
||||
ship.Hull.Hardpoints[0].Rotation = ItemRotation.Clockwise;
|
||||
ship.Validate();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidatorRefusesANullRecord() =>
|
||||
Assert.Contains("is null", Assert.Throws<InvalidOperationException>(() => ShipAuthoringStore.Validate(ShipAuthoringTests.Fixture().Hull, null)).Message);
|
||||
|
|
@ -151,7 +162,7 @@ public sealed class ShipValidationTests
|
|||
Add("hull-width-zero", s => s.Hull.Shape.Cells = new bool[0, 2], "at least one cell");
|
||||
Add("hull-height-zero", s => s.Hull.Shape.Cells = new bool[2, 0], "at least one cell");
|
||||
Add("hull-no-occupied-cell", s => s.Hull.Shape.Cells = new bool[2, 2], "at least one cell");
|
||||
Add("hull-names-a-prefab", s => s.Hull.Prefab = "Djinni", "cannot name a Unity prefab");
|
||||
Add("hull-names-a-prefab-and-a-visual", s => s.Hull.Prefab = "Djinni", "names both a Unity prefab and a visual record");
|
||||
Add("model-null", s => s.Visual.ModelAsset = null, "relative package path");
|
||||
Add("model-blank", s => s.Visual.ModelAsset = " ", "relative package path");
|
||||
|
||||
|
|
@ -169,6 +180,10 @@ public sealed class ShipValidationTests
|
|||
Add("role-doubled-" + role, s => s.Visual.Anchors.Add(new ShipAnchor { Id = "extra", Role = role, ModelNodeId = "extra" }), $"exactly one {role} anchor is required");
|
||||
}
|
||||
|
||||
Add("anchor-role-unknown", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "x", Role = "engine", ModelNodeId = "x" }), "has unknown role 'engine'");
|
||||
Add("anchor-role-null", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "x", Role = null, ModelNodeId = "x" }), "has unknown role ''");
|
||||
Add("anchor-role-cased", s => s.Visual.Anchors[0].Role = "Map-Icon", "has unknown role 'Map-Icon'");
|
||||
|
||||
Add("hardpoint-null", s => s.Hull.Hardpoints.Add(null), "hardpoint IDs must be present and unique");
|
||||
Add("hardpoint-transform-null", s => Mount(s).Transform = null, "hardpoint IDs must be present and unique");
|
||||
Add("hardpoint-transform-blank", s => Mount(s).Transform = " ", "hardpoint IDs must be present and unique");
|
||||
|
|
@ -176,6 +191,16 @@ public sealed class ShipValidationTests
|
|||
Add("hardpoint-shape-null", s => Mount(s).Shape = null, "has no cells");
|
||||
Add("hardpoint-cells-null", s => Mount(s).Shape.Cells = null, "has no cells");
|
||||
Add("hardpoint-cells-all-empty", s => Mount(s).Shape.Cells = new bool[1, 1], "has no cells");
|
||||
Add("hardpoint-type-undefined", s => Mount(s).Type = (HardpointType)99, "unknown type 99");
|
||||
Add("hardpoint-type-negative", s => Mount(s).Type = (HardpointType)(-1), "unknown type -1");
|
||||
Add("hardpoint-rotation-undefined", s => Mount(s).Rotation = (ItemRotation)4, "unknown rotation 4");
|
||||
Add("hardpoint-rotation-negative", s => Mount(s).Rotation = (ItemRotation)(-1), "unknown rotation -1");
|
||||
Add("hardpoint-armor-nan", s => Mount(s).Armor = float.NaN, "armor and firing arc must be finite and not negative");
|
||||
Add("hardpoint-armor-infinite", s => Mount(s).Armor = float.PositiveInfinity, "armor and firing arc must be finite and not negative");
|
||||
Add("hardpoint-armor-negative", s => Mount(s).Armor = -1, "armor and firing arc must be finite and not negative");
|
||||
Add("hardpoint-arc-nan", s => Mount(s).FiringArc = float.NaN, "armor and firing arc must be finite and not negative");
|
||||
Add("hardpoint-arc-infinite", s => Mount(s).FiringArc = float.NegativeInfinity, "armor and firing arc must be finite and not negative");
|
||||
Add("hardpoint-arc-negative", s => Mount(s).FiringArc = -1, "armor and firing arc must be finite and not negative");
|
||||
Add("hardpoint-left-of-hull", s => Mount(s).Position = new int2(-1, 0), "outside the hull schematic");
|
||||
Add("hardpoint-below-hull", s => Mount(s).Position = new int2(1, -1), "outside the hull schematic");
|
||||
Add("hardpoint-right-of-hull", s => Mount(s).Position = new int2(2, 0), "outside the hull schematic");
|
||||
|
|
|
|||
|
|
@ -18,8 +18,9 @@ SCHEMA = "aetheria.ship_authoring"
|
|||
HULL_SCHEMA = "aetheria.hulldata"
|
||||
|
||||
# MessagePack slots of the C# types, which own them (ShipAuthoring, ItemData.Shape, HullData.Hardpoints,
|
||||
# HardpointData). ShipSchemaPinTests in tests/Aetheria.Shared.Tests fails when any number or name below
|
||||
# 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
|
||||
# disagrees with those types' [Key] attributes, so a renumbered or added member cannot drift silently.
|
||||
RETIRED_HULL_SLOT = 1
|
||||
SCHEMATIC_LINES_SLOT = 4 # ShipAuthoring.SchematicLines
|
||||
HULL_SHAPE_SLOT = 5 # ItemData.Shape
|
||||
HULL_HARDPOINTS_SLOT = 23 # HullData.Hardpoints
|
||||
|
|
@ -69,6 +70,14 @@ def read(path: str, cultlib_packages: str) -> ShipFile:
|
|||
envelopes = store.pull_all()
|
||||
ships = [envelope for envelope in envelopes if envelope.type == SCHEMA]
|
||||
hulls = [envelope for envelope in envelopes if envelope.type == HULL_SCHEMA]
|
||||
# Before S1 the hull lived inside the ship record. Saving such a file would preserve the stale hull under a ship that
|
||||
# no longer reads it, so it is refused before anything else is said about its shape.
|
||||
for envelope in ships:
|
||||
body = msgpack.unpackb(envelope.payload, raw=False)
|
||||
if isinstance(body, list) and len(body) > RETIRED_HULL_SLOT and body[RETIRED_HULL_SLOT] is not None:
|
||||
raise ValueError(
|
||||
f"{path}: {envelope.key}: 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"{path} must hold exactly one {SCHEMA} record and one {HULL_SCHEMA} record")
|
||||
bodies = []
|
||||
|
|
@ -129,6 +138,8 @@ def replace_layout(path: str, cultlib_packages: str, expected_id: str, expected_
|
|||
width, height, cells = shape
|
||||
if not (1 <= width <= 32 and 1 <= height <= 32 and len(cells) == width * height):
|
||||
raise ValueError("Hull grid must be 1..32 cells wide and high with one value per cell")
|
||||
if not all(type(cell) is bool for cell in cells):
|
||||
raise ValueError("Hull grid cells must be booleans")
|
||||
if not any(cells):
|
||||
raise ValueError("Hull grid needs an occupied cell")
|
||||
known = len(HARDPOINT_MEMBERS)
|
||||
|
|
@ -141,6 +152,8 @@ def replace_layout(path: str, cultlib_packages: str, expected_id: str, expected_
|
|||
if len(hardpoint) != known or not isinstance(mount, str) or not mount:
|
||||
raise ValueError(f"Each hardpoint needs {known} typed fields and a stable mount ID")
|
||||
hp_width, hp_height, hp_cells = fields["Shape"][0]
|
||||
if not all(type(cell) is bool for cell in hp_cells):
|
||||
raise ValueError(f"Hardpoint {mount} footprint cells must be booleans")
|
||||
if not (1 <= hp_width <= 32 and 1 <= hp_height <= 32 and
|
||||
len(hp_cells) == hp_width * hp_height and any(hp_cells)):
|
||||
raise ValueError(f"Hardpoint {mount} has an invalid footprint")
|
||||
|
|
|
|||
|
|
@ -8,12 +8,14 @@ ship_cc is loaded by path because the package __init__ imports bpy. The record l
|
|||
ship_cc's own slot constants; ShipSchemaPinTests (C#) pins those constants to the C# [Key] attributes.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
|
@ -140,11 +142,42 @@ class ReadTests(ShipFileCase):
|
|||
with self.assertRaisesRegex(ValueError, "must hold exactly one"):
|
||||
ship_cc.read(empty, PACKAGES)
|
||||
|
||||
def test_refuses_a_ship_payload_too_short_for_the_line_slot(self):
|
||||
self.write(["mod.skiff", None], hull_body())
|
||||
with self.assertRaisesRegex(ValueError, "incompatible"):
|
||||
def test_refuses_a_ship_record_that_still_carries_the_retired_embedded_hull(self):
|
||||
for name, ship in (("nested hull", ["mod.skiff", hull_body()]),
|
||||
("any value", ["mod.skiff", 0])):
|
||||
body = ship_body()
|
||||
body[ship_cc.RETIRED_HULL_SLOT] = ship[1]
|
||||
with self.subTest(name):
|
||||
self.write(body, hull_body())
|
||||
with self.assertRaisesRegex(ValueError, "legacy embedded hull at retired key 1"):
|
||||
ship_cc.read(self.path, PACKAGES)
|
||||
# Nothing else is said about its shape: an old file has no hull record beside the ship.
|
||||
cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all(
|
||||
[envelope("mod-ship:mod.skiff", ship_cc.SCHEMA, CATALOG, body)])
|
||||
with self.assertRaisesRegex(ValueError, "legacy embedded hull"):
|
||||
ship_cc.read(self.path, PACKAGES)
|
||||
|
||||
def test_refuses_a_save_over_a_file_with_the_retired_embedded_hull_and_writes_nothing(self):
|
||||
body = ship_body()
|
||||
body[ship_cc.RETIRED_HULL_SLOT] = hull_body()
|
||||
self.write(body, hull_body())
|
||||
before = self.bytes()
|
||||
with self.assertRaisesRegex(ValueError, "legacy embedded hull"):
|
||||
ship_cc.replace_lines(self.path, PACKAGES, LINES)
|
||||
with self.assertRaisesRegex(ValueError, "legacy embedded hull"):
|
||||
ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", "any", [2, 2, [True] * 4], [])
|
||||
self.assertEqual(before, self.bytes())
|
||||
|
||||
def test_a_nil_in_the_retired_slot_is_the_current_shape(self):
|
||||
self.assertIsNone(self.ship()[ship_cc.RETIRED_HULL_SLOT])
|
||||
|
||||
def test_refuses_a_ship_payload_too_short_for_the_line_slot(self):
|
||||
for body in (["mod.skiff"], ["mod.skiff", None]):
|
||||
with self.subTest(slots=len(body)):
|
||||
self.write(body, hull_body())
|
||||
with self.assertRaisesRegex(ValueError, "incompatible"):
|
||||
ship_cc.read(self.path, PACKAGES)
|
||||
|
||||
def test_refuses_a_payload_that_is_not_an_array(self):
|
||||
for payload in ({"Id": "mod.skiff"}, {str(index): index for index in range(9)}, "a string long enough to fill every slot"):
|
||||
with self.subTest(ship=payload):
|
||||
|
|
@ -168,6 +201,17 @@ class ReplaceLinesTests(ShipFileCase):
|
|||
if slot != ship_cc.SCHEMATIC_LINES_SLOT:
|
||||
self.assertEqual(before[slot], after[slot], f"slot {slot} changed")
|
||||
|
||||
def test_a_save_refreshes_the_stored_at_of_the_record_it_writes_and_only_that_one(self):
|
||||
stale = "2000-01-01T00:00:00+00:00"
|
||||
envelopes = self.envelopes()
|
||||
cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all(
|
||||
[dataclasses.replace(envelopes[key], stored_at=stale) for key in envelopes])
|
||||
ship_cc.replace_lines(self.path, PACKAGES, LINES)
|
||||
after = self.envelopes()
|
||||
self.assertGreater(datetime.fromisoformat(after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].stored_at),
|
||||
datetime.fromisoformat(stale))
|
||||
self.assertEqual(stale, after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")].stored_at)
|
||||
|
||||
def test_leaves_the_hull_record_byte_identical(self):
|
||||
before = self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")]
|
||||
ship_cc.replace_lines(self.path, PACKAGES, LINES)
|
||||
|
|
@ -294,6 +338,38 @@ class LayoutTests(ShipFileCase):
|
|||
revision = self.layout()[2]
|
||||
self.assertNotEqual(before, self.bytes())
|
||||
|
||||
def test_a_layout_save_refreshes_the_stored_at_of_the_hull_and_leaves_the_ships(self):
|
||||
stale = "2000-01-01T00:00:00+00:00"
|
||||
envelopes = self.envelopes()
|
||||
cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all(
|
||||
[dataclasses.replace(envelopes[key], stored_at=stale) for key in envelopes])
|
||||
self.edit(self.layout()[2])
|
||||
after = self.envelopes()
|
||||
self.assertGreater(datetime.fromisoformat(after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")].stored_at),
|
||||
datetime.fromisoformat(stale))
|
||||
self.assertEqual(stale, after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].stored_at)
|
||||
|
||||
def test_refuses_cells_that_are_not_booleans_and_writes_nothing(self):
|
||||
_, _, revision = self.layout()
|
||||
before = self.bytes()
|
||||
for name, cells in (("integer", [True, 1, True, False]), ("zero", [True, True, True, 0]),
|
||||
("string", [True, "x", True, False]), ("none", [True, None, True, False])):
|
||||
with self.subTest(name):
|
||||
with self.assertRaisesRegex(ValueError, "Hull grid cells must be booleans"):
|
||||
self.edit(revision, cells=cells)
|
||||
self.assertEqual(before, self.bytes())
|
||||
|
||||
def test_refuses_hardpoint_footprint_cells_that_are_not_booleans_and_writes_nothing(self):
|
||||
_, _, revision = self.layout()
|
||||
before = self.bytes()
|
||||
for name, cells in (("integer", [1, True]), ("none", [True, None])):
|
||||
row = ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(hardpoint_row(tail=())),
|
||||
"Shape": [shape(2, 1, cells)]})
|
||||
with self.subTest(name):
|
||||
with self.assertRaisesRegex(ValueError, "thruster.port footprint cells must be booleans"):
|
||||
self.edit(revision, hardpoints=[row])
|
||||
self.assertEqual(before, self.bytes())
|
||||
|
||||
def test_refuses_a_cell_count_that_does_not_fill_the_grid(self):
|
||||
_, _, revision = self.layout()
|
||||
before = self.bytes()
|
||||
|
|
|
|||
Loading…
Reference in a new issue