diff --git a/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs new file mode 100644 index 000000000..b892c1908 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// tools/blender/aetheria_ships/ship_cc.py edits a ShipAuthoring record by MessagePack slot number and by hardpoint +// member position. These tests bind that file to the C# types that own the numbers: any renumbered, renamed or +// reordered member, enum value, or nested array shape fails here instead of corrupting a ship the next time Blender saves. +public sealed class ShipSchemaPinTests +{ + private static readonly string Source = File.ReadAllText(Locate("tools", "blender", "aetheria_ships", "ship_cc.py")); + + [Theory] + [InlineData("SCHEMATIC_LINES_SLOT", typeof(ShipAuthoring), nameof(ShipAuthoring.SchematicLines))] + [InlineData("HULL_SLOT", typeof(ShipAuthoring), nameof(ShipAuthoring.Hull))] + [InlineData("HULL_SHAPE_SLOT", typeof(HullData), nameof(HullData.Shape))] + [InlineData("HULL_HARDPOINTS_SLOT", typeof(HullData), nameof(HullData.Hardpoints))] + public void PythonSlotConstantsAreTheKeysOfTheMembersTheyNameInTheirComments(string constant, Type owner, string member) + { + Assert.Equal(KeyOf(owner, member), Integer(constant)); + Assert.Matches(new Regex($@"^{constant} = \d+ # \w+\.{member}\r?$", RegexOptions.Multiline), Source); + } + + [Fact] + public void PythonHardpointMembersAreHardpointDataMembersAtTheirOwnPositions() + { + var members = Strings("HARDPOINT_MEMBERS"); + Assert.Equal(7, members.Length); + for (var slot = 0; slot < members.Length; slot++) + Assert.Equal(slot, KeyOf(typeof(HardpointData), members[slot])); + } + + [Fact] + public void PythonEnumNamesAreTheEnumsInValueOrder() + { + Assert.Equal(EnumNames(), Strings("HARDPOINT_TYPE_NAMES")); + Assert.Equal(EnumNames(), Strings("ROTATION_NAMES")); + } + + [Fact] + public void SerializedShipHasTheNestedArrayShapesPythonIndexes() + { + var ship = ShipAuthoringTests.Fixture(); + var bytes = MessagePackSerializer.Serialize(ship, CultDocumentMessagePackSerialization.OptionsFor(typeof(ShipAuthoring).Assembly)); + var body = Assert.IsType(MessagePackSerializer.Deserialize(bytes, MessagePackSerializerOptions.Standard)); + + Assert.Equal("mod.skiff", body[0]); + var hull = Assert.IsType(body[Integer("HULL_SLOT")]); + // A schematic is [[width, height, cells]] with cells flattened x-major (index x * height + y). + var hullShape = Assert.IsType(Assert.IsType(hull[Integer("HULL_SHAPE_SLOT")])[0]); + Assert.Equal(new object[] { 2, 2 }, hullShape.Take(2).Select(value => (object)Convert.ToInt32(value))); + Assert.Equal(new[] { true, false, true, false }, Assert.IsType(hullShape[2]).Cast()); + + var hardpoints = Assert.IsType(hull[Integer("HULL_HARDPOINTS_SLOT")]); + var row = Assert.IsType(Assert.Single(hardpoints)); + var members = Strings("HARDPOINT_MEMBERS"); + Assert.True(row.Length >= members.Length); + Assert.Equal("thruster.port", row[Array.IndexOf(members, "Transform")]); + var footprint = Assert.IsType(Assert.IsType(row[Array.IndexOf(members, "Shape")])[0]); + Assert.Equal(3, footprint.Length); + Assert.Equal(new[] { true }, Assert.IsType(footprint[2]).Cast()); + Assert.Equal(new[] { 1, 0 }, Assert.IsType(row[Array.IndexOf(members, "Position")]).Select(value => Convert.ToInt32(value))); + + var lines = Assert.IsType(body[Integer("SCHEMATIC_LINES_SLOT")]); + Assert.Equal("Hull", Assert.IsType(Assert.Single(lines))[0]); + } + + private static int KeyOf(Type owner, string member) + { + var found = owner.GetMember(member, BindingFlags.Public | BindingFlags.Instance).Single(); + return Assert.IsType(found.GetCustomAttribute().IntKey); + } + + private static int Integer(string constant) => + int.Parse(Regex.Match(Source, $@"^{constant} = (\d+)", RegexOptions.Multiline).Groups[1].Value); + + private static string[] Strings(string constant) + { + var block = Regex.Match(Source, $@"^{constant} = \((.*?)\)\r?$", RegexOptions.Multiline | RegexOptions.Singleline); + Assert.True(block.Success, $"{constant} is not a tuple in ship_cc.py"); + return Regex.Matches(block.Groups[1].Value, "\"([^\"]*)\"").Select(match => match.Groups[1].Value).ToArray(); + } + + private static string[] EnumNames() where T : struct, Enum + { + var values = Enum.GetValues().OrderBy(value => Convert.ToInt32(value)).ToArray(); + Assert.Equal(Enumerable.Range(0, values.Length), values.Select(value => Convert.ToInt32(value))); + return values.Select(value => value.ToString()).ToArray(); + } + + private static string Locate(params string[] relative) + { + for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory != null; directory = directory.Parent) + { + var candidate = Path.Combine(new[] { directory.FullName }.Concat(relative).ToArray()); + if (File.Exists(candidate)) return candidate; + } + throw new FileNotFoundException("Repository file not found above the test binary: " + Path.Combine(relative)); + } +} diff --git a/tools/blender/aetheria_ships/__init__.py b/tools/blender/aetheria_ships/__init__.py index b12a7b38e..e84c4332d 100644 --- a/tools/blender/aetheria_ships/__init__.py +++ b/tools/blender/aetheria_ships/__init__.py @@ -12,15 +12,12 @@ bl_info = { import bpy -from .ship_cc import capture_grease_pencil, read, read_layout, replace_layout, replace_lines +from .ship_cc import (HARDPOINT_TYPE_NAMES, ROTATION_NAMES, capture_grease_pencil, decode_hardpoint, + encode_hardpoint, read, read_layout, replace_layout, replace_lines) -HARDPOINT_TYPES = tuple((str(i), name, name) for i, name in enumerate(( - "Hull", "Tool", "Thermal", "Thruster", "WarpDrive", "Reactor", "Radiator", - "Shield", "Sensors", "Energy", "Ballistic", "Launcher", "ControlModule", "AetherDrive", -))) -ROTATIONS = (("0", "None", "None"), ("1", "Counterclockwise", "Counterclockwise"), - ("2", "Reversed", "Reversed"), ("3", "Clockwise", "Clockwise")) +HARDPOINT_TYPES = tuple((str(i), name, name) for i, name in enumerate(HARDPOINT_TYPE_NAMES)) +ROTATIONS = tuple((str(i), name, name) for i, name in enumerate(ROTATION_NAMES)) class AETHERIA_PG_cell(bpy.types.PropertyGroup): @@ -97,14 +94,15 @@ class AETHERIA_OT_load_layout(bpy.types.Operator): state.cells.add().occupied = bool(cell) state.hardpoints.clear() for raw in hardpoints: + fields = decode_hardpoint(raw) hp = state.hardpoints.add() - hp.kind = str(raw[0]) - hp.x, hp.y = raw[1] - hp.footprint = _footprint(raw[2]) - hp.mount_id = raw[3] or "" - hp.rotation = str(raw[4]) - hp.armor = raw[5] - hp.firing_arc = raw[6] + hp.kind = str(fields["Type"]) + hp.x, hp.y = fields["Position"] + hp.footprint = _footprint(fields["Shape"]) + hp.mount_id = fields["Transform"] or "" + hp.rotation = str(fields["Rotation"]) + hp.armor = fields["Armor"] + hp.firing_arc = fields["FiringArc"] self.report({"INFO"}, f"Loaded {width}x{height} layout and {len(hardpoints)} hardpoints") return {"FINISHED"} except (OSError, ValueError, RuntimeError, ImportError, KeyError) as exc: @@ -165,8 +163,9 @@ class AETHERIA_OT_save_layout(bpy.types.Operator): if state.ship_id != collection["aetheria.id"] or state.ship_cc != path: raise ValueError("Load this collection's layout before saving") cells = [cell.occupied for cell in state.cells] - hardpoints = [[int(hp.kind), [hp.x, hp.y], _parse_footprint(hp.footprint), - hp.mount_id, int(hp.rotation), hp.armor, hp.firing_arc] + hardpoints = [encode_hardpoint( + Type=int(hp.kind), Position=[hp.x, hp.y], Shape=_parse_footprint(hp.footprint), + Transform=hp.mount_id, Rotation=int(hp.rotation), Armor=hp.armor, FiringArc=hp.firing_arc) for hp in state.hardpoints] state.revision = replace_layout( path, _brokkr_cultlib(context), state.ship_id, state.revision, diff --git a/tools/blender/aetheria_ships/ship_cc.py b/tools/blender/aetheria_ships/ship_cc.py index 727db49e0..54064b598 100644 --- a/tools/blender/aetheria_ships/ship_cc.py +++ b/tools/blender/aetheria_ships/ship_cc.py @@ -15,10 +15,31 @@ from pathlib import Path from typing import Any SCHEMA = "aetheria.ship_authoring" -SCHEMATIC_LINES_SLOT = 4 -HULL_SLOT = 1 -HULL_SHAPE_SLOT = 5 -HULL_HARDPOINTS_SLOT = 23 + +# 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 +# disagrees with those types' [Key] attributes, so a renumbered or added member cannot drift silently. +SCHEMATIC_LINES_SLOT = 4 # ShipAuthoring.SchematicLines +HULL_SLOT = 1 # ShipAuthoring.Hull +HULL_SHAPE_SLOT = 5 # ItemData.Shape +HULL_HARDPOINTS_SLOT = 23 # HullData.Hardpoints +# HardpointData member names in slot order; a hardpoint row is one value per name, and any slot past the last +# name belongs to a later schema and is carried through untouched. +HARDPOINT_MEMBERS = ("Type", "Position", "Shape", "Transform", "Rotation", "Armor", "FiringArc") +# Enum member names in value order (HardpointType, ItemRotation). +HARDPOINT_TYPE_NAMES = ("Hull", "Tool", "Thermal", "Thruster", "WarpDrive", "Reactor", "Radiator", + "Shield", "Sensors", "Energy", "Ballistic", "Launcher", "ControlModule", "AetherDrive") +ROTATION_NAMES = ("None", "CounterClockwise", "Reversed", "Clockwise") + + +def decode_hardpoint(row: list[Any]) -> dict[str, Any]: + return dict(zip(HARDPOINT_MEMBERS, row)) + + +def encode_hardpoint(**fields: Any) -> list[Any]: + if set(fields) != set(HARDPOINT_MEMBERS): + raise ValueError(f"A hardpoint row needs exactly {', '.join(HARDPOINT_MEMBERS)}") + return [fields[name] for name in HARDPOINT_MEMBERS] def _libraries(cultlib_packages: str): @@ -85,17 +106,20 @@ def replace_layout(path: str, cultlib_packages: str, expected_id: str, expected_ raise ValueError("Hull grid must be 1..32 cells wide and high with one value per cell") if not any(cells): raise ValueError("Hull grid needs an occupied cell") - previous = {hp[3]: hp[7:] for hp in body[HULL_SLOT][HULL_HARDPOINTS_SLOT] - if isinstance(hp, list) and len(hp) > 7 and isinstance(hp[3], str)} + known = len(HARDPOINT_MEMBERS) + previous = {decode_hardpoint(hp)["Transform"]: hp[known:] for hp in hull[HULL_HARDPOINTS_SLOT] + if isinstance(hp, list) and len(hp) > known and isinstance(decode_hardpoint(hp)["Transform"], str)} updated_hardpoints = [] for hardpoint in hardpoints: - if len(hardpoint) != 7 or not isinstance(hardpoint[3], str) or not hardpoint[3]: - raise ValueError("Each hardpoint needs seven typed fields and a stable mount ID") - hp_width, hp_height, hp_cells = hardpoint[2][0] + fields = decode_hardpoint(hardpoint) + mount = fields.get("Transform") + 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 (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 {hardpoint[3]} has an invalid footprint") - updated_hardpoints.append(hardpoint + previous.get(hardpoint[3], [])) + raise ValueError(f"Hardpoint {mount} has an invalid footprint") + updated_hardpoints.append(hardpoint + previous.get(mount, [])) hull[HULL_SHAPE_SLOT] = [shape] hull[HULL_HARDPOINTS_SLOT] = updated_hardpoints store.push(replace( diff --git a/tools/blender/tests/test_ship_cc.py b/tools/blender/tests/test_ship_cc.py new file mode 100644 index 000000000..ab9eb6299 --- /dev/null +++ b/tools/blender/tests/test_ship_cc.py @@ -0,0 +1,370 @@ +"""Blender-free tests for aetheria_ships/ship_cc.py, the Python view of a typed ShipAuthoring record. + +Run with CultLib's cultcache-py and msgpack importable: + + CULTLIB_PACKAGES=/packages python -m unittest discover -s tools/blender/tests + +ship_cc is loaded by path because the package __init__ imports bpy. The record layout the tests build comes from +ship_cc's own slot constants; ShipSchemaPinTests (C#) pins those constants to the C# [Key] attributes. +""" + +import importlib.util +import os +import sys +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +PACKAGES = os.environ.get("CULTLIB_PACKAGES") +if not PACKAGES: + raise RuntimeError("Set CULTLIB_PACKAGES to CultLib's packages directory") + +_spec = importlib.util.spec_from_file_location( + "ship_cc", Path(__file__).resolve().parents[1] / "aetheria_ships" / "ship_cc.py") +ship_cc = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(ship_cc) + +sys.path.insert(0, str(Path(PACKAGES) / "cultcache-py" / "src")) +import cultcache_py # noqa: E402 +import msgpack # noqa: E402 + + +def shape(width, height, cells): + return [width, height, cells] + + +def hardpoint_row(mount="thruster.port", tail=("future-hardpoint-slot",)): + row = ship_cc.encode_hardpoint( + Type=3, Position=[1, 0], Shape=[shape(1, 1, [True])], Transform=mount, Rotation=0, Armor=0.0, FiringArc=0.0) + return row + list(tail) + + +def hull_slots(): + hull = [None] * (ship_cc.HULL_HARDPOINTS_SLOT + 1) + hull[1] = "Skiff" + hull[ship_cc.HULL_SHAPE_SLOT] = [shape(2, 2, [True, False, True, False])] + hull[ship_cc.HULL_HARDPOINTS_SLOT] = [hardpoint_row()] + hull.append("future-hull-slot") + return hull + + +LINES = [["Hull", "White", [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.01, 0.01], [1.0, 1.0], False, [1.0, 1.0, 1.0, 1.0]]] + + +def ship_body(): + body = [None] * (ship_cc.SCHEMATIC_LINES_SLOT + 1) + body[0] = "mod.skiff" + body[ship_cc.HULL_SLOT] = hull_slots() + body[2] = "skiff.glb" + body[3] = [["map", "map-icon", "map", None, 0]] + body[ship_cc.SCHEMATIC_LINES_SLOT] = LINES + return body + + +CATALOG = cultcache_py.CultCacheSchemaCatalogEntry( + schema_id="ship-authoring-schema-1", schema_name=ship_cc.SCHEMA, schema_version="1", + content_hash="hash", canonical_schema_json='{"members":[{"slot":9,"name":"FutureMember"}]}', + compatible_schema_ids=("ship-authoring-schema-1",), + members=(cultcache_py.CultCacheSchemaCatalogMember(slot=9, member_name="FutureMember", type_name="string"),)) + + +class ShipFileCase(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.path = str(Path(directory.name) / "ship.cc") + self.write(ship_body()) + + def write(self, body, path=None): + cultcache_py.SingleFileMessagePackBackingStore(path or self.path).push(cultcache_py.CultCacheEnvelope.create( + key="mod.skiff", type=ship_cc.SCHEMA, payload=msgpack.packb(body, use_bin_type=True), + schema_id=CATALOG.schema_id, catalog_entry=CATALOG)) + + def body(self): + return ship_cc.read(self.path, PACKAGES)[2] + + def bytes(self): + return Path(self.path).read_bytes() + + +class ReadTests(ShipFileCase): + def test_reads_the_one_ship_record(self): + store, envelope, body, _ = ship_cc.read(self.path, PACKAGES) + self.assertEqual("mod.skiff", body[0]) + self.assertEqual(ship_cc.SCHEMA, envelope.type) + + def test_refuses_a_file_with_another_record_beside_the_ship(self): + cultcache_py.SingleFileMessagePackBackingStore(self.path).push(cultcache_py.CultCacheEnvelope.create( + key="other", type="aetheria.something", payload=msgpack.packb([1], use_bin_type=True))) + with self.assertRaisesRegex(ValueError, "must hold exactly one"): + ship_cc.read(self.path, PACKAGES) + + def test_refuses_a_file_with_no_record(self): + empty = str(Path(self.path).with_name("empty.cc")) + Path(empty).write_bytes(b"") + with self.assertRaisesRegex(ValueError, "must hold exactly one"): + ship_cc.read(empty, PACKAGES) + + def test_refuses_a_payload_too_short_for_the_line_slot(self): + self.write(["mod.skiff", None]) + with self.assertRaisesRegex(ValueError, "incompatible"): + ship_cc.read(self.path, PACKAGES) + + def test_refuses_a_payload_that_is_not_an_array(self): + self.write({"Id": "mod.skiff"}) + with self.assertRaisesRegex(ValueError, "incompatible"): + ship_cc.read(self.path, PACKAGES) + + +class ReplaceLinesTests(ShipFileCase): + def test_replaces_only_the_line_slot(self): + new_lines = [["Detail", "Red", [0.0] * 6, [0.1, 0.1], [1.0, 1.0], True, [1.0, 0.0, 0.0, 1.0]]] + before = self.body() + self.assertEqual(1, ship_cc.replace_lines(self.path, PACKAGES, new_lines)) + after = self.body() + self.assertEqual(new_lines, after[ship_cc.SCHEMATIC_LINES_SLOT]) + for slot in range(len(before)): + if slot != ship_cc.SCHEMATIC_LINES_SLOT: + self.assertEqual(before[slot], after[slot], f"slot {slot} changed") + + def test_keeps_the_schema_catalog(self): + ship_cc.replace_lines(self.path, PACKAGES, LINES) + envelope = cultcache_py.SingleFileMessagePackBackingStore(self.path).pull_all()[0] + self.assertEqual(CATALOG.members, envelope.catalog_entry.members) + self.assertEqual(CATALOG.canonical_schema_json, envelope.catalog_entry.canonical_schema_json) + + def test_refuses_an_empty_capture_and_changes_nothing(self): + before = self.bytes() + with self.assertRaisesRegex(ValueError, "No Grease Pencil strokes"): + ship_cc.replace_lines(self.path, PACKAGES, []) + self.assertEqual(before, self.bytes()) + + +class LayoutTests(ShipFileCase): + def layout(self): + return ship_cc.read_layout(self.path, PACKAGES) + + def edit(self, revision, width=2, height=2, cells=None, hardpoints=None, ship_id="mod.skiff"): + return ship_cc.replace_layout( + self.path, PACKAGES, ship_id, revision, + [width, height, cells if cells is not None else [True, True, True, False]], + hardpoints if hardpoints is not None else [hardpoint_row(tail=())]) + + def test_reads_the_shape_hardpoints_and_a_revision(self): + shape_triple, hardpoints, revision = self.layout() + self.assertEqual([2, 2, [True, False, True, False]], shape_triple) + self.assertEqual("thruster.port", ship_cc.decode_hardpoint(hardpoints[0])["Transform"]) + self.assertEqual(64, len(revision)) + + def test_the_revision_follows_the_layout_and_only_the_layout(self): + _, _, revision = self.layout() + body = self.body() + body[ship_cc.SCHEMATIC_LINES_SLOT] = [] + body[ship_cc.HULL_SLOT][1] = "Renamed" + self.write(body) + self.assertEqual(revision, self.layout()[2]) + body[ship_cc.HULL_SLOT][ship_cc.HULL_SHAPE_SLOT] = [shape(2, 2, [True, True, True, True])] + self.write(body) + self.assertNotEqual(revision, self.layout()[2]) + + def test_saves_the_layout_and_returns_the_new_revision(self): + _, _, revision = self.layout() + moved = hardpoint_row(tail=()) + moved[1] = [0, 0] + returned = self.edit(revision, cells=[True, True, True, False], hardpoints=[moved]) + shape_triple, hardpoints, saved = self.layout() + self.assertEqual([2, 2, [True, True, True, False]], shape_triple) + self.assertEqual([0, 0], ship_cc.decode_hardpoint(hardpoints[0])["Position"]) + self.assertEqual(saved, returned) + self.assertNotEqual(revision, returned) + + def test_preserves_every_slot_it_does_not_edit(self): + _, _, revision = self.layout() + before = self.body() + self.edit(revision) + after = self.body() + for slot in range(len(before)): + if slot != ship_cc.HULL_SLOT: + self.assertEqual(before[slot], after[slot], f"ship slot {slot} changed") + for slot in range(len(before[ship_cc.HULL_SLOT])): + if slot not in (ship_cc.HULL_SHAPE_SLOT, ship_cc.HULL_HARDPOINTS_SLOT): + self.assertEqual(before[ship_cc.HULL_SLOT][slot], after[ship_cc.HULL_SLOT][slot], f"hull slot {slot} changed") + + def test_carries_a_later_schemas_hardpoint_slots_by_mount_id(self): + _, _, revision = self.layout() + starboard = hardpoint_row("thruster.starboard", tail=()) + self.edit(revision, hardpoints=[starboard, hardpoint_row(tail=())]) + rows = self.layout()[1] + self.assertEqual(["thruster.starboard", "thruster.port"], [ship_cc.decode_hardpoint(row)["Transform"] for row in rows]) + self.assertEqual(len(ship_cc.HARDPOINT_MEMBERS), len(rows[0])) + self.assertEqual(["future-hardpoint-slot"], rows[1][len(ship_cc.HARDPOINT_MEMBERS):]) + + def test_drops_the_row_of_a_removed_mount(self): + _, _, revision = self.layout() + self.edit(revision, hardpoints=[]) + self.assertEqual([], self.layout()[1]) + + def test_keeps_the_schema_catalog(self): + _, _, revision = self.layout() + self.edit(revision) + envelope = cultcache_py.SingleFileMessagePackBackingStore(self.path).pull_all()[0] + self.assertEqual(CATALOG.members, envelope.catalog_entry.members) + + def test_refuses_a_ship_id_that_changed_and_writes_nothing(self): + _, _, revision = self.layout() + before = self.bytes() + with self.assertRaisesRegex(ValueError, "bound ship ID changed"): + self.edit(revision, ship_id="mod.other") + self.assertEqual(before, self.bytes()) + + def test_refuses_a_stale_revision_and_writes_nothing(self): + _, _, revision = self.layout() + self.edit(revision) + before = self.bytes() + with self.assertRaisesRegex(ValueError, "layout changed since Load"): + self.edit(revision) + self.assertEqual(before, self.bytes()) + + def test_refuses_grid_sizes_outside_one_to_thirty_two_and_writes_nothing(self): + _, _, revision = self.layout() + before = self.bytes() + for width, height in ((0, 2), (2, 0), (33, 1), (1, 33)): + with self.subTest(width=width, height=height): + with self.assertRaisesRegex(ValueError, "1..32 cells"): + self.edit(revision, width=width, height=height, cells=[True] * (width * height)) + for width, height in ((1, 1), (32, 32)): + with self.subTest(width=width, height=height): + self.edit(revision, width=width, height=height, cells=[True] * (width * height), hardpoints=[]) + revision = self.layout()[2] + self.assertNotEqual(before, self.bytes()) + + def test_refuses_a_cell_count_that_does_not_fill_the_grid(self): + _, _, revision = self.layout() + before = self.bytes() + with self.assertRaisesRegex(ValueError, "1..32 cells"): + self.edit(revision, cells=[True, True, True]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_grid_with_no_occupied_cell(self): + _, _, revision = self.layout() + with self.assertRaisesRegex(ValueError, "needs an occupied cell"): + self.edit(revision, cells=[False] * 4) + + def test_refuses_a_hardpoint_row_of_the_wrong_arity_or_without_a_mount_id(self): + _, _, revision = self.layout() + before = self.bytes() + row = hardpoint_row(tail=()) + for name, bad in (("short", row[:-1]), ("long", row + [0]), + ("blank", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": ""})), + ("none", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": None})), + ("number", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": 4}))): + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "stable mount ID"): + self.edit(revision, hardpoints=[bad]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_hardpoint_footprint_that_is_not_a_filled_grid_of_one_to_thirty_two(self): + _, _, revision = self.layout() + before = self.bytes() + for name, footprint in (("no width", shape(0, 1, [])), ("no height", shape(1, 0, [])), + ("too wide", shape(33, 1, [True] * 33)), ("too tall", shape(1, 33, [True] * 33)), + ("short", shape(2, 1, [True])), ("empty", shape(1, 1, [False]))): + row = ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(hardpoint_row(tail=())), "Shape": [footprint]}) + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "thruster.port has an invalid footprint"): + self.edit(revision, hardpoints=[row]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_payload_without_the_hull_hardpoint_slot(self): + body = self.body() + body[ship_cc.HULL_SLOT] = body[ship_cc.HULL_SLOT][:ship_cc.HULL_HARDPOINTS_SLOT] + self.write(body) + with self.assertRaisesRegex(ValueError, "incompatible typed payload"): + self.layout() + + +class HardpointRowTests(unittest.TestCase): + def test_a_row_is_one_value_per_member_in_slot_order(self): + fields = dict(Type=1, Position=[2, 3], Shape="shape", Transform="mount", Rotation=2, Armor=4.0, FiringArc=90.0) + row = ship_cc.encode_hardpoint(**fields) + self.assertEqual([fields[name] for name in ship_cc.HARDPOINT_MEMBERS], row) + self.assertEqual(fields, ship_cc.decode_hardpoint(row)) + + def test_encoding_needs_every_member_and_no_other(self): + good = dict.fromkeys(ship_cc.HARDPOINT_MEMBERS, 0) + with self.assertRaises(ValueError): + ship_cc.encode_hardpoint(**{name: 0 for name in ship_cc.HARDPOINT_MEMBERS[1:]}) + with self.assertRaises(ValueError): + ship_cc.encode_hardpoint(**good, Extra=1) + + +class Matrix: + """Stands in for mathutils.Matrix: a translation by (10, 20, 30).""" + + def __matmul__(self, position): + return tuple(value + offset for value, offset in zip(position, (10.0, 20.0, 30.0))) + + +def point(x, radius=0.5, opacity=1.0): + return SimpleNamespace(position=(x, 0.0, 0.0), radius=radius, opacity=opacity) + + +def stroke(points, material_index=0, cyclic=False): + return SimpleNamespace(points=points, material_index=material_index, cyclic=cyclic) + + +def frame(number, strokes): + return SimpleNamespace(frame_number=number, drawing=SimpleNamespace(strokes=strokes)) + + +def layer(name, frames): + return SimpleNamespace(name=name, frames=frames) + + +def grease_pencil(layers, materials): + return SimpleNamespace(type="GREASEPENCIL", matrix_world=Matrix(), data=SimpleNamespace(layers=layers, materials=materials)) + + +class CaptureTests(unittest.TestCase): + def test_refuses_an_object_that_is_not_grease_pencil(self): + with self.assertRaisesRegex(ValueError, "is not a Grease Pencil object"): + ship_cc.capture_grease_pencil(SimpleNamespace(type="MESH", name="Cube"), None, 1) + + def test_captures_the_latest_frame_at_or_before_the_current_one(self): + materials = [SimpleNamespace(name="Ink", grease_pencil=SimpleNamespace(color=(0.1, 0.2, 0.3, 1.0)))] + obj = grease_pencil([layer("Hull", [frame(1, [stroke([point(1.0), point(2.0)])]), + frame(5, [stroke([point(3.0), point(4.0)])]), + frame(9, [stroke([point(5.0), point(6.0)])])])], materials) + lines = ship_cc.capture_grease_pencil(obj, None, 5, evaluated=False) + self.assertEqual([["Hull", "Ink", [13.0, 20.0, 30.0, 14.0, 20.0, 30.0], [0.5, 0.5], [1.0, 1.0], False, + [0.1, 0.2, 0.3, 1.0]]], lines) + self.assertEqual(13.0, ship_cc.capture_grease_pencil(obj, None, 6, evaluated=False)[0][2][0]) + self.assertEqual(11.0, ship_cc.capture_grease_pencil(obj, None, 1, evaluated=False)[0][2][0]) + + def test_skips_layers_without_a_frame_yet_and_strokes_of_one_point(self): + obj = grease_pencil([layer("Later", [frame(7, [stroke([point(1.0), point(2.0)])])]), + layer("Now", [frame(1, [stroke([point(1.0)]), stroke([point(1.0), point(2.0)], cyclic=True)])])], + [SimpleNamespace(name="Plain", grease_pencil=None, diffuse_color=(0.4, 0.5, 0.6, 1.0))]) + lines = ship_cc.capture_grease_pencil(obj, None, 3, evaluated=False) + self.assertEqual(1, len(lines)) + self.assertEqual(["Now", "Plain"], lines[0][:2]) + self.assertTrue(lines[0][5]) + self.assertEqual([0.4, 0.5, 0.6, 1.0], lines[0][6]) + + def test_a_stroke_without_a_material_is_white_and_unnamed(self): + obj = grease_pencil([layer("Hull", [frame(1, [stroke([point(1.0), point(2.0)])])])], [None]) + line = ship_cc.capture_grease_pencil(obj, None, 1, evaluated=False)[0] + self.assertEqual(["Hull", ""], line[:2]) + self.assertEqual([1.0, 1.0, 1.0, 1.0], line[6]) + + def test_reads_strokes_from_the_evaluated_copy_but_transforms_by_the_source_object(self): + evaluated = grease_pencil([layer("Baked", [frame(1, [stroke([point(1.0), point(2.0)])])])], [None]) + source = grease_pencil([layer("Raw", [frame(1, [stroke([point(1.0), point(2.0)])])])], [None]) + source.evaluated_get = lambda depsgraph: evaluated + self.assertEqual("Baked", ship_cc.capture_grease_pencil(source, "graph", 1)[0][0]) + self.assertEqual("Raw", ship_cc.capture_grease_pencil(source, "graph", 1, evaluated=False)[0][0]) + + +if __name__ == "__main__": + unittest.main()