Rewire package_hull, compare, gen_manifest and job.ps1 over ship-authoring open

This commit is contained in:
soul 2026-11-28 05:04:50 +01:00
commit 2d94e1c709
6 changed files with 63 additions and 79 deletions

View file

@ -1,38 +1,39 @@
"""compare.py <committed ship.cc> <derived ship.cc>: exit 0 and COMPARE_EQUAL when the two packages hold the same shape, rows (id,
type, cell, footprint, rotation, armour, arc), stats, price and product (maker, name, description, offered), both read through
aetheria_ships/ship_cc.py. GLB bytes are not compared. Needs CULTLIB_PACKAGES."""
import importlib.util
"""compare.py <committed ship.cc> <derived ship.cc>: exit 0 and COMPARE_EQUAL when the two packages hold the same grid, hardpoint
rows (mount, kind, cell, footprint, rotation, armour, arc, in order), hull section (name, price, stats, top speed, kind) and
products (maker, name, description, offered), both read through AetherDb's 'ship-authoring open'. GLB bytes are not compared.
Needs GAME_FOLDER, whose ModTools holds AetherDb."""
import json
import os
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location("ship_cc", HERE.parent / "aetheria_ships" / "ship_cc.py")
sc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(sc)
P = os.environ["CULTLIB_PACKAGES"]
sys.path.insert(0, str(Path(P) / "cultcache-py" / "src"))
import msgpack
def opened(path):
"""'ship-authoring open' of a ship.cc as a dict."""
game = Path(os.environ["GAME_FOLDER"])
tool = game / "ModTools" / ("AetherDb.exe" if sys.platform == "win32" else "AetherDb")
run = subprocess.run([str(tool), "ship-authoring", "open", str(path)], cwd=game, capture_output=True, text=True, timeout=120)
if run.returncode != 0:
sys.exit(f"open refused {path}: {run.stdout.strip()} {run.stderr.strip()}")
return json.loads(run.stdout)
def view(path):
f = sc.read(path, P)
shape, rows, _ = sc.read_layout(path, P)
b = f.hull.body
limit = [p for u, p in b[11] if u == 11][0][1]
prods = [msgpack.unpackb(e.payload, raw=False) for e in f.store.pull_all() if e.type == sc.PRODUCT_SCHEMA]
return {"shape": shape, "rows": [sc.decode_hardpoint(r) for r in rows], "name": b[1], "mass": b[4], "price": b[8],
"durability": b[12], "armor": b[27], "drag": b[28], "top": (limit[0], limit[1]), "makers": sc.product_makers(path, P),
"products": [(p[1], p[2], p[8]) for p in prods]}
o = opened(path)
return {"grid": o["layout"]["grid"],
"rows": [{k: v for k, v in row.items() if k != "element"} for row in o["layout"]["hardpoints"]],
"hull": o["hull"], "products": o["products"]}
a, b = view(sys.argv[1]), view(sys.argv[2])
bad = [k for k in a if a[k] != b[k]]
for k in bad:
print("DIFF", k, *([] if k == "rows" else [a[k], b[k]]))
if "rows" in bad:
for x, y in zip(a["rows"], b["rows"]):
if x != y:
print("DIFF row", x, y)
print("COMPARE_EQUAL" if not bad else "COMPARE_DIFFERENT", len(a["rows"]), "rows")
sys.exit(1 if bad else 0)
if __name__ == "__main__":
a, b = view(sys.argv[1]), view(sys.argv[2])
bad = [k for k in a if a[k] != b[k]]
for k in bad:
print("DIFF", k, *([] if k == "rows" else [a[k], b[k]]))
if "rows" in bad:
for x, y in zip(a["rows"], b["rows"]):
if x != y:
print("DIFF row", x, y)
print("COMPARE_EQUAL" if not bad else "COMPARE_DIFFERENT", len(a["rows"]), "rows")
sys.exit(1 if bad else 0)

View file

@ -1,27 +1,17 @@
"""gen_manifest.py <ship.cc> <hull.scad> <out.json> --like <hull name> --extent X Y Z --maker <faction name> [--length N]
A packager manifest (see ../package_hull.md) from an existing package's ship.cc, read through aetheria_ships/ship_cc.py: rows,
stats, price and product come from the .cc; the arguments are what a .cc does not record (the hull to copy, the model extent in
metres, the maker, the schematic length in cells). The id is the package folder's name. The hull.scad is copied beside the
manifest. Needs CULTLIB_PACKAGES.
A packager manifest (see ../package_hull.md) from an existing package's ship.cc, read through AetherDb's 'ship-authoring
open': rows, stats, price and product come from the .cc; the arguments are what a .cc does not record (the hull to copy, the
model extent in metres, the maker, the schematic length in cells). The id is the package folder's name. The hull.scad is
copied beside the manifest. Needs GAME_FOLDER, whose ModTools holds AetherDb.
"""
import argparse
import importlib.util
import json
import os
import shutil
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location("ship_cc", HERE.parent / "aetheria_ships" / "ship_cc.py")
sc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(sc)
def footprint(raw):
w, h, cells = raw[0]
return "/".join("".join("#" if cells[x * h + y] else "." for x in range(w)) for y in range(h - 1, -1, -1))
from compare import opened
def main():
@ -34,27 +24,26 @@ def main():
parser.add_argument("--maker", required=True)
parser.add_argument("--length", type=int, default=30)
args = parser.parse_args()
packages = os.environ["CULTLIB_PACKAGES"]
sys.path.insert(0, str(Path(packages) / "cultcache-py" / "src"))
import msgpack
f = sc.read(args.ship_cc, packages)
_, rows, _ = sc.read_layout(args.ship_cc, packages)
body = f.hull.body
if sc.read_hull_type(args.ship_cc, packages) == "Station":
o = opened(args.ship_cc)
hull = o["hull"]
if o["hullType"] == "Station":
sys.exit("gen_manifest reads a ship: a station has no top speed and its kind is not in the hull record. "
"Station manifests are written by hand (see manifests/arsenal-depot, package_hull.md).")
limit = [p for u, p in body[11] if u == 11][0][1]
assert limit[0] == limit[1], "the manifest holds one top speed"
product = [msgpack.unpackb(e.payload, raw=False) for e in f.store.pull_all() if e.type == sc.PRODUCT_SCHEMA][0]
if hull["topSpeed"] is None:
sys.exit("the hull has no single fixed top speed; the manifest holds one")
if len(o["products"]) != 1:
sys.exit(f"the package holds {len(o['products'])} products; the manifest holds one")
product = o["products"][0]
manifest = {
"id": Path(args.ship_cc).resolve().parent.name,
"name": body[1], "like": args.like, "length": args.length, "extent": args.extent,
"hull": Path(args.hull_scad).name, "maker": args.maker, "description": product[2], "offered": not product[8],
"price": body[8],
"stats": {"mass": body[4], "durability": body[12], "armor": body[27], "drag": round(body[28], 6), "top_speed": limit[0]},
"rows": [{"id": d["Transform"], "kind": sc.HARDPOINT_TYPE_NAMES[d["Type"]], "cell": list(d["Position"]),
"footprint": footprint(d["Shape"]), "rotation": d["Rotation"], "armor": d["Armor"], "arc": d["FiringArc"]}
for d in map(sc.decode_hardpoint, rows)],
"name": hull["name"], "like": args.like, "length": args.length, "extent": args.extent,
"hull": Path(args.hull_scad).name, "maker": args.maker, "description": product["description"],
"offered": product["offered"], "price": hull["price"],
"stats": {"mass": hull["mass"], "durability": hull["durability"], "armor": hull["armor"],
"drag": round(hull["drag"], 6), "top_speed": hull["topSpeed"]},
"rows": [{"id": row["mount"], "kind": row["kind"], "cell": row["cell"], "footprint": row["footprint"],
"rotation": row["rotation"], "armor": row["armor"], "arc": row["arc"]}
for row in o["layout"]["hardpoints"]],
}
out = Path(args.out)
out.write_text(json.dumps(manifest, indent=1), encoding="utf-8")

View file

@ -1,4 +1,4 @@
# job.ps1 -Scratch <dir> -Game <folder> [-Blender <exe>] [-OpenScad <exe>] [-Packages <dir>] [-Lock <starfire_lock.py>]
# job.ps1 -Scratch <dir> -Game <folder> [-Blender <exe>] [-OpenScad <exe>] [-Lock <starfire_lock.py>]
# The packager's regression job: package_hull.py on the fixture manifest; on a manifest generated from the committed
# aetheria.nakovalnya package, compared (compare.py) with that package; a second run without --replace (must refuse and leave
# the package byte-identical); a --replace that fails (must leave it byte-identical); and AetherDb compose over the result.
@ -10,7 +10,6 @@ param(
[Parameter(Mandatory)] [string]$Game,
[string]$Blender = "C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe",
[string]$OpenScad = "C:\Tools\OpenSCAD-2026.09.23-x86-64\openscad.com",
[string]$Packages = "F:\Projects\CultLib\packages",
[string]$Lock = "F:\Projects\eureka-handoff-aux-2026-10-19\starfire_lock.py"
)
$ErrorActionPreference = "Stop"
@ -36,15 +35,7 @@ State "waiting for the Starfire lock"
if (Test-Path $Lock) { & py -3 $Lock acquire hull-packager 2>&1 | ForEach-Object { Say $_ } }
try {
$env:GAME_FOLDER = $Game
$env:CULTLIB_PACKAGES = $Packages
$env:OPENSCAD = $OpenScad
# Blender's Python needs msgpack: PYTHONPATH, unless set, is the newest Blender user-site scripts\modules that holds it.
if (-not $env:PYTHONPATH) {
$site = Get-ChildItem "$env:APPDATA\Blender Foundation\Blender" -Directory | Sort-Object { [version]$_.Name } -Descending |
Where-Object { Test-Path "$($_.FullName)\scripts\modules\msgpack" } | Select-Object -First 1
if (-not $site) { throw "no Blender user site holds msgpack; install it with Blender's Python (pip --target <user>\scripts\modules)" }
$env:PYTHONPATH = "$($site.FullName)\scripts\modules"
}
$Fixture = "$Repo\tools\blender\tests\fixtures\hulls\zh-ammo-tender\package.json"
$Committed = "$Repo\GameData\Mods\aetheria.nakovalnya"
$Mods = "$Game\GameData\Mods"

View file

@ -2,7 +2,7 @@
One bench hull plus one manifest becomes one ship package (`GameData/Mods/<id>/ship.cc`, `ship.glb`, `hull.scad`) that the
validator accepts, with no Unity and no clicking. The header of `package_hull.py` gives the command line, the environment
(`GAME_FOLDER`, `CULTLIB_PACKAGES`, `OPENSCAD`) and the order of steps. This file is the manifest schema and the way to check the
(`GAME_FOLDER`, `OPENSCAD`) and the order of steps. This file is the manifest schema and the way to check the
packager still matches the committed first-party package.
## Contract
@ -55,7 +55,7 @@ The committed example is `tests/fixtures/hulls/zh-ammo-tender/package.json`; its
- `build_aetherdb.ps1` publishes `tools/AetherDb` into `<game>/ModTools`: it needs CultLib and CultMath worktrees at the revisions
`Directory.Build.props` names and passes `ErrorOnDuplicatePublishOutputFiles=false` (the NETSDK1152 workaround).
- `manifests/arsenal-depot/` is the committed manifest of the Arsenal Depot (its `hull.scad` is a copy of the package's; a test holds both equal to the shipped package, `Fa.1` included): a station's manifest is written by hand, and `gen_manifest.py` refuses a station with a message.
- `gen_manifest.py <ship.cc> <hull.scad> <out.json> --like ... --extent X Y Z --maker ...` turns an existing package into a manifest.
- `gen_manifest.py <ship.cc> <hull.scad> <out.json> --like ... --extent X Y Z --maker ...` turns an existing package into a manifest. `gen_manifest.py` and `compare.py` read through AetherDb's `ship-authoring open` and need `GAME_FOLDER`.
- `compare.py <committed ship.cc> <derived ship.cc>` prints `COMPARE_EQUAL` when shape, rows, stats, price and product match.
- `job.ps1` runs the regression on a workstation with Blender and OpenSCAD: the fixture manifest; the committed
`aetheria.nakovalnya` regenerated from its own manifest and compared; a refused second run and a failed `--replace`, each

View file

@ -2,7 +2,7 @@
blender --background --factory-startup --python-use-system-env --python tools/blender/package_hull.py -- <manifest.json> [--replace]
Environment: GAME_FOLDER (holds GameData/Aetheria.cc and ModTools/AetherDb.exe), CULTLIB_PACKAGES, OPENSCAD. The repo (and so the
Environment: GAME_FOLDER (holds GameData/Aetheria.cc and ModTools/AetherDb.exe) and OPENSCAD. The repo (and so the
add-on) is found from this file. The manifest is creation input only: once GameData/Mods/<id> exists, ship.cc owns rows, stats and
product, and a manifest is never read again; --replace re-derives the package and discards edits made since. Without --replace an
existing package is refused untouched. A run is all or nothing: --replace moves the existing package aside, builds, and deletes the old one
@ -183,7 +183,7 @@ def rows_of(manifest):
for row in manifest["rows"]]
def package(manifest, manifest_dir, game, packages, openscad):
def package(manifest, manifest_dir, game, openscad):
"""The Blender half, run inside swap(). Builds GameData/Mods/<id>; raises Refused with a message on any failure."""
import addon_utils
import bmesh
@ -250,6 +250,9 @@ def package(manifest, manifest_dir, game, packages, openscad):
if "top_speed" in stats:
args += ["--top-speed", stats["top_speed"]]
require(db(*args) == 0, "stats was refused")
if "top_speed" in stats:
require(aetheria_ships._open(bpy.context, str(ship_cc_path))["hull"]["topSpeed"] == stats["top_speed"],
"stats did not set the top speed")
if "kind" in manifest:
# A station's kind is ship.cc's own fact and AetherDb its one writer; the packager holds no kind table.
require(db("kind", ship_cc_path, manifest["kind"]) == 0, "kind was refused")
@ -308,7 +311,7 @@ def main(argv):
if len(paths) != 1:
raise Refused("usage: package_hull.py -- <manifest.json> [--replace]")
env = {}
for key in ("GAME_FOLDER", "CULTLIB_PACKAGES", "OPENSCAD"):
for key in ("GAME_FOLDER", "OPENSCAD"):
if not os.environ.get(key):
raise Refused(f"Set {key}")
env[key] = os.environ[key]
@ -316,7 +319,7 @@ def main(argv):
manifest = load_manifest(manifest_path)
game = Path(env["GAME_FOLDER"])
with swap(game / "GameData" / "Mods" / manifest["id"], game / f".hull-packager-backup-{manifest['id']}", replace):
package(manifest, manifest_path.parent, game, env["CULTLIB_PACKAGES"], env["OPENSCAD"])
package(manifest, manifest_path.parent, game, env["OPENSCAD"])
def entry(argv):

View file

@ -115,7 +115,7 @@ class SwapTests(unittest.TestCase):
self.manifest.write_text(json.dumps(data), encoding="utf-8")
(root / data["hull"]).write_text("// hull" + chr(10), encoding="utf-8")
self.package_dir = self.game / "GameData" / "Mods" / self.id
old = mock.patch.dict(os.environ, {"GAME_FOLDER": str(self.game), "CULTLIB_PACKAGES": "x", "OPENSCAD": "x"})
old = mock.patch.dict(os.environ, {"GAME_FOLDER": str(self.game), "OPENSCAD": "x"})
old.start()
self.addCleanup(old.stop)
self.real = ph.package
@ -131,7 +131,7 @@ class SwapTests(unittest.TestCase):
return [(str(p.relative_to(self.game)), p.read_bytes() if p.is_file() else None) for p in files]
def builder(self, then):
def package(manifest, manifest_dir, game, packages, openscad):
def package(manifest, manifest_dir, game, openscad):
self.package_dir.mkdir(parents=True, exist_ok=True)
(self.package_dir / "ship.cc").write_bytes(b"derived")
(self.package_dir / "hull.scad").write_bytes(b"half built")