diff --git a/tools/blender/aetheria_ships/__init__.py b/tools/blender/aetheria_ships/__init__.py index a447c1ead..e52f4ffd1 100644 --- a/tools/blender/aetheria_ships/__init__.py +++ b/tools/blender/aetheria_ships/__init__.py @@ -1524,7 +1524,7 @@ def _frame_ship(context, collection, root, path, saved_shape): _recentre(root, hull_grid.cell_centre((float(origin[0]), float(origin[1])), centre[0], centre[1])) -HULL_SOURCE_MARK = "aetheria.hull_source" # set on every object Build From Hull Source makes; Build replaces only these +HULL_BUILT = "aetheria.hull_built" # on the collection: {object name: fingerprint} of what Build From Hull Source made HULL_COLLIDER = ("hull-collider", "collider", "Hull Collider") @@ -1537,8 +1537,24 @@ def _hull_source_file(collection): return source if source.is_file() else None -def _hull_source_objects(collection): - return [obj for obj in collection.all_objects if obj.get(HULL_SOURCE_MARK)] +def _fingerprint(obj): + """What Build made of obj, as it stands: its place under its parent, the anchor properties and, for a mesh, its geometry. + A copy has another name and an edit changes this, so neither is taken for Build's own.""" + values = [obj.parent.name if obj.parent else "", tuple(obj.location), tuple(obj.rotation_euler), tuple(obj.scale), + obj.get("aetheria.role", ""), obj.get("aetheria.id", ""), obj.get("aetheria.order", 0)] + if obj.type == "MESH": + values += [[tuple(v.co) for v in obj.data.vertices], [tuple(p.vertices) for p in obj.data.polygons]] + return hull_source.fingerprint(*values) + + +def _hull_built(collection): + """(untouched, changed): Build's objects found in the collection as it made them, and those it made that were edited. + The record is the only owner: an object is Build's when its name and fingerprint are the ones recorded.""" + record = collection.get(HULL_BUILT) + record = record.to_dict() if record is not None else {} + present = {obj.name: obj for obj in collection.all_objects if obj.name in record} + untouched = [obj for name, obj in present.items() if _fingerprint(obj) == record[name]] + return untouched, [obj for obj in present.values() if obj not in untouched] def _hull_material(ship_id, zone, colour, emissive=False): @@ -1567,7 +1583,7 @@ def _hull_mesh(name, mesh, material, offset=(0.0, 0.0, 0.0), yaw=0.0): return data -def _build_hull_source(context, collection, runner=None): +def _build_hull_source(context, collection): """Replaces the objects Build made before with the hull source's zone meshes, anchors and collider under Ship Root. Refuses, before anything changes, when the source cannot be read, breaks a check of its faction's language, or the collection holds render meshes Build did not make (operator art: Build never overwrites it). Writes no layout row.""" @@ -1575,14 +1591,16 @@ def _build_hull_source(context, collection, runner=None): if source is None: raise ValueError("The bound package holds no hull.scad") root = _ship_root(collection) + untouched, changed = _hull_built(collection) if root is not None: _refuse_loose_meshes(context, collection) - if any(not obj.get(HULL_SOURCE_MARK) for obj in _own_meshes(collection)): - raise ValueError("The collection holds meshes the hull source did not make; Build From Hull Source " - "replaces only its own objects") + theirs = [obj for obj in _own_meshes(collection) if obj not in untouched] + if theirs or changed: + raise ValueError("The collection holds meshes the hull source did not make, or objects it made that were " + "changed; Build From Hull Source replaces only what it made and nobody touched") addon = context.preferences.addons.get(__package__) executable = addon.preferences.openscad if addon and addon.preferences else DEFAULT_OPENSCAD - hull = hull_source.build(runner or hull_source.openscad_runner(executable, source)) + hull = hull_source.build(hull_source.openscad_runner(executable, source), hull_source.language_library(executable)) broken = hull.failed() if broken: raise ValueError("The hull source breaks its faction's language or its brief: " + "; ".join(c.name for c in broken)) @@ -1591,11 +1609,12 @@ def _build_hull_source(context, collection, runner=None): root = bpy.data.objects.new(SHIP_ROOT, None) root["aetheria.ship_root"] = True collection.objects.link(root) - for obj in _hull_source_objects(collection): + for obj in untouched: _discard_object(obj) + made = [] def mark(obj): - obj[HULL_SOURCE_MARK] = True + made.append(obj) return obj def link(obj): @@ -1631,18 +1650,25 @@ def _build_hull_source(context, collection, runner=None): collider = link(bpy.data.objects.new(name, _hull_mesh( name, hull.zones[hull.body_zone], _hull_material(ship_id, "collider", (0.5, 0.5, 0.5))))) collider["aetheria.role"], collider["aetheria.id"] = role, anchor_id + collection[HULL_BUILT] = {obj.name: _fingerprint(obj) for obj in made} return hull def _retire_hull_source(collection): - """Deletes the package's hull.scad when operator art is what was packaged: the collection holds render meshes and - none of Build's objects. A hull never built, or built and packaged as it stands, keeps its source. Returns whether the - file was deleted.""" + """Deletes the package's hull.scad when the body is the operator's: the collection holds render meshes that Build did + not make as they stand, and no zone mesh of Build's is left. The anchors and collider she kept are hers from then on. + A hull never built, or built and packaged as it stands, keeps its source. Returns whether the file was deleted.""" source = _hull_source_file(collection) root = _ship_root(collection) - if source is None or root is None or _hull_source_objects(collection) or not _own_meshes(collection): + if source is None or root is None: + return False + untouched, _ = _hull_built(collection) + zones = [obj for obj in untouched if obj.type == "MESH" and "aetheria.role" not in obj] + if zones or not [obj for obj in _own_meshes(collection) if obj not in untouched]: return False source.unlink() + if HULL_BUILT in collection: + del collection[HULL_BUILT] return True diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py index f66c27810..08fa00b57 100644 --- a/tools/blender/aetheria_ships/hull_source.py +++ b/tools/blender/aetheria_ships/hull_source.py @@ -1,11 +1,14 @@ """Agent-built hulls: reads a hull.scad through OpenSCAD and judges it against its faction's form language. No bpy import. A hull source is a GameData/Mods//hull.scad that includes its faction's language file (and, for a -Pirate hull, its donor's) from factions/. Everything the add-on needs is echoed by one part of that file: +Pirate hull, its donor's) from factions/. Everything the add-on needs is echoed by one part of that file. The faction's language is owned by its own file in +factions/: the checks read it from there, by the faction the brief names, and the hull's own `lang` echo is only compared +with it (a hull that redefines or shadows an included language fails a check): brief ECHO brief = [faction, donor, role, [length_min, length_max], [tris_min, tris_max], reads] lang ECHO lang = [faction, [[zone, [r, g, b]], ...], body zone, glow, radiator, proportion, symmetry] - (every included language file echoes its own; a Pirate language has no body zone and no proportion) + (every included language file echoes its own, and so does factions/.scad run alone; a Pirate + language has no body zone and no proportion) anchors ECHO anchor = [id, role, [x, y, z], yaw, parent] one line per anchor, yaw 0 nose, 90 port the zone's geometry, OFF; a donor's zone is named ":" emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor @@ -14,6 +17,7 @@ Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. build() returns a HullBu check. Messages and check names are fixed text: nothing a hull source says is echoed back. """ +import hashlib import json import math import os @@ -31,6 +35,7 @@ SILHOUETTE_CELL = 0.25 # metres, the top-view raster the symmetry check compare ANCHOR_ROLES = ("weapon-mount", "weapon-muzzle", "thruster-emitter", "radiator-mesh") MESH_ROLES = {"thruster-emitter": "emit:", "radiator-mesh": "rad:"} ECHO_PARTS = ("brief", "lang", "anchors") # parts that make no geometry; their ECHO lines are the answer +LANGUAGE_NAME = re.compile(r"[a-z][a-z0-9_]*") ECHO_LINE = re.compile(r"^ECHO: (\w+) = (.*)$", re.MULTILINE) # A runner answers one part of the hull source with (OFF text, ECHO text). OFF text is "" when the part made no geometry. @@ -146,6 +151,23 @@ def parse_echoes(text, name): return values +def fingerprint(*values): + """A digest of numbers, strings and the lists of them, floats to five decimals: equal exactly when the values are.""" + digest = hashlib.sha256() + + def add(value): + if isinstance(value, (list, tuple)): + digest.update(b"[") + for item in value: + add(item) + digest.update(b"]") + else: + digest.update((f"{round(value, 5) + 0.0:.5f};" if isinstance(value, float) else f"{value!r};").encode()) + + add(values) + return digest.hexdigest() + + def _vector(value, size, numbers=True): if not isinstance(value, list) or len(value) != size or (numbers and not all(_number(v) for v in value)): raise HullSourceError("The hull source echoed a vector of the wrong shape") @@ -179,7 +201,8 @@ def _proportion(raw): def read_languages(text): - languages = {} + """Every language echoed in text, in echo order.""" + languages = [] for raw in parse_echoes(text, "lang"): if not isinstance(raw, list) or len(raw) != 7 or not isinstance(raw[1], list): raise HullSourceError("A faction language has the wrong shape") @@ -194,7 +217,7 @@ def read_languages(text): symmetry) if language.body and language.body not in language.zone_names(): raise HullSourceError("A faction language's body zone is not one of its zones") - languages[language.faction] = language + languages.append(language) return languages @@ -238,17 +261,25 @@ def _triangles_xy(mesh): return [tuple(mesh.vertices[v][:2] for v in tri) for tri in mesh.triangles] -def build(runner): - """Reads the hull source through runner (see Runner) and judges it. Raises HullSourceError when the source cannot be - read at all; otherwise returns a HullBuild whose failed() lists the checks it breaks.""" +def _language(library, faction): + """The language of factions/.scad, which owns it: exactly one echo, naming that faction.""" + (language,) = _exactly_one(read_languages(library(faction)), "language") + if language.faction != faction: + raise HullSourceError("A faction language file echoes the language of another faction") + return language + + +def build(runner, library): + """Reads the hull source through runner (see Runner) and judges it against the languages library(faction) answers with + (the ECHO text of that faction's own language file). Raises HullSourceError when the source cannot be read at all; + otherwise returns a HullBuild whose failed() lists the checks it breaks.""" _, text = runner("brief") brief = read_brief(text) _, text = runner("lang") - languages = read_languages(text) - own = languages.get(brief.faction) - donor = languages.get(brief.donor) if brief.donor else None - if own is None or (brief.donor and donor is None): - raise HullSourceError("The hull source does not include the language of its faction or its donor") + included = read_languages(text) + own = _language(library, brief.faction) + donor = _language(library, brief.donor) if brief.donor else None + owned = [own] + ([donor] if donor else []) zone_keys = list(own.zone_names()) + [f"{donor.faction}:{z}" for z in (donor.zone_names() if donor else ())] colours = {z: own.colour(z) for z in own.zone_names()} colours.update({f"{donor.faction}:{z}": donor.colour(z) for z in (donor.zone_names() if donor else ())}) @@ -261,8 +292,12 @@ def build(runner): anchor_meshes = {a.id: parse_off(runner(MESH_ROLES[a.role] + a.id)[0]) for a in anchors if a.role in MESH_ROLES} judge = donor or own body_zone = f"{donor.faction}:{donor.body}" if donor else own.body - result = HullBuild(brief, languages, zones, colours, anchors, anchor_meshes, own.glow, own.radiator, body_zone) - result.checks = _checks(result, own, judge) + result = HullBuild(brief, {language.faction: language for language in owned}, zones, colours, anchors, anchor_meshes, + own.glow, own.radiator, body_zone) + by_faction = lambda language: language.faction + result.checks = [Check("the hull includes its faction's language files and changes none of them", + sorted(included, key=by_faction) == sorted(owned, key=by_faction), "")] + result.checks += _checks(result, own, judge) return result @@ -342,3 +377,15 @@ def openscad_runner(executable, source, library=FACTIONS_DIR, on_start=None): return ("", written + output) if part in ECHO_PARTS else (written, output) return run + + +def language_library(executable, library=FACTIONS_DIR, on_start=None): + """The `library` build() reads languages from: faction -> the ECHO text of library/.scad run alone, so a hull + source (or a file beside it) cannot stand in for the faction's own file.""" + def read(faction): + file = library / f"{faction}.scad" + if not LANGUAGE_NAME.fullmatch(faction) or not file.is_file(): + raise HullSourceError("The hull source names a faction that has no language file") + return openscad_runner(executable, file, library=library, on_start=on_start)("lang")[1] + + return read diff --git a/tools/blender/tests/smoke_hull_source.py b/tools/blender/tests/smoke_hull_source.py index b2e803349..cabfddfd8 100644 --- a/tools/blender/tests/smoke_hull_source.py +++ b/tools/blender/tests/smoke_hull_source.py @@ -13,16 +13,23 @@ Rossum & Douglas wedge) the smoke makes a ship from a stand-in box (New Ship), a the hull.scad into the package and runs the panel's operators: Build: zone meshes with one palette material each, the mount anchors, the emitter and radiator meshes and a collider, - all marked aetheria.hull_source under Ship Root, and no layout row changed by Build itself. + all recorded on the collection by name and fingerprint under Ship Root, each at the pose the hull source gives it + (a mount yawed 90 degrees included), and no layout row changed by Build itself. A second Build replaces only its own objects: an object the author made, a mesh and an empty, is still there. Build refuses, naming a rule and no input, a hull source that breaks its language's or brief's rule, and changes nothing. - Build refuses a collection that holds a render mesh it did not make, and changes nothing. - Package accepts the built ship (the C# validator), writes ship.glb with a node per anchor, and leaves hull.scad. - Once the author has taken the generated objects over (the mark is gone) Package deletes hull.scad and says so. + Build refuses a hull source that redefines or shadows its faction's language (reassigned variable, second echo, a + language file beside the hull), and changes nothing. + Build refuses, and changes nothing, a collection that holds a render mesh it did not make, a copy of a generated zone, + or a generated zone or mount that was edited in place. + Package accepts the built ship (the C# validator), writes ship.glb with a node per anchor, and leaves hull.scad; a + Build after Package still works. + The author replaces the zone meshes with her art and keeps Build's anchors and collider: Package deletes hull.scad in + that one act and says so, and Build then refuses. A hull that was never built keeps its hull.scad through the same deletion rule. """ import json +import math import os import shutil import struct @@ -57,6 +64,18 @@ HULLS = ( ) +# per fixture: the variable the hull's language is in, a value that redefines it (every rule loosened), the language file a +# copy of which beside hull.scad would shadow the include, and a colour in it +ATTACKS = { + "zh-ammo-tender": ("ZH_LANG", '["zhestokost", ZH_ZONES, "primary", ZH_GLOW, ZH_RADIATOR, [[0, 9], [0, 9]], ["asymmetric", 0.0]]', + "zhestokost.scad", "[0.42, 0.43, 0.45]"), + "pi-fighter": ("PI_LANG", '["pirate", PI_ZONES, "", PI_GLOW, PI_RADIATOR, [], ["bilateral", 0.0]]', + "pirate.scad", "[0.48, 0.27, 0.22]"), +} +EXECUTABLE = None # the OpenSCAD the add-on preference names, set by main +hull_source = None # aetheria_ships.hull_source, set by main + + def require(condition, message): if not condition: raise SystemExit(message) @@ -79,7 +98,9 @@ def approx(a, b, tolerance=1e-3): def generated(collection): - return {obj.name: obj for obj in collection.all_objects if obj.get("aetheria.hull_source")} + """Build's objects, by the record Build keeps on the collection.""" + record = collection.get("aetheria.hull_built") + return {obj.name: obj for obj in collection.all_objects if record is not None and obj.name in record} def layout_rows(scene): @@ -151,6 +172,8 @@ def one_hull(scene, number, fixture, ship_id, extent, length, rows, body, palett root = bpy.data.objects[next(o.name for o in collection.all_objects if o.get("aetheria.ship_root"))] rows_before = layout_rows(scene) source = package / "hull.scad" + lang_var, lang_value, shadowed, shadow_colour = ATTACKS[fixture] + runner = hull_source.openscad_runner(EXECUTABLE, source) require(source.is_file(), "The fixture hull.scad was not copied") require("Build From Hull Source" == bpy.ops.aetheria.build_hull_source.get_rna_type().name, "Build is not registered") @@ -169,6 +192,11 @@ def one_hull(scene, number, fixture, ship_id, extent, length, rows, body, palett require(mount.get("aetheria.role") == "weapon-mount" and first[muzzle].get("aetheria.order") == 1, "A muzzle is not ordered under its mount") require(first[muzzle].matrix_world.translation.y < mount.matrix_world.translation.y, "A muzzle is not nose-ward of its mount") require(layout_rows(scene) == rows_before, "Build changed the layout buffer") + check_poses(collection, root, runner) + if fixture == "zh-ammo-tender": + original = source.read_text(encoding="utf-8") + yawed_mount(scene, box, collection, root, package, source, original, runner) + first = generated(collection) print(f"PASS {number}.1 {fixture} builds: {len(first)} objects, {sum(len(v) for v in roles.values())} anchors") # A second Build replaces only its own objects; the author's own empty and mesh (outside render meshes' reach: a mesh @@ -234,19 +262,144 @@ def one_hull(scene, number, fixture, ship_id, extent, length, rows, body, palett f"{[(hp.mount_id, (hp.x, hp.y)) for hp in moved]} (authored at {[r[2] for r in rows if r[1] == BALLISTIC]})") print(f"PASS {number}.5 Package accepts the built ship and keeps hull.scad") - # The author takes the generated objects over: Package deletes hull.scad and says so. - for obj in generated(collection).values(): - del obj["aetheria.hull_source"] + # What Package did to the built objects is not an edit: Build still replaces them. + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"FINISHED"}, f"Build after Package was refused: {message!r}") + print(f"PASS {number}.6 Build after Package replaces its own objects") + + # A hull source that redefines or shadows its faction's language: refused, nothing changes. + attacks = [] + for label, change in ( + ("reassigns the language after the include", lambda text: text + f"\n{lang_var} = {lang_value};\n"), + ("echoes a second language", lambda text: text + f'\nif (part == "lang") echo(lang = {lang_value});\n')): + attacks.append((label, lambda change=change: source.write_text(change(original), encoding="utf-8"), lambda: None)) + shadow = package / shadowed + shadow_text = (REPO / "tools" / "blender" / "aetheria_ships" / "factions" / shadowed).read_text(encoding="utf-8") + require(shadow_text.count(shadow_colour) >= 1, "The shadow's colour is not in the language file") + attacks.append(("shadows the language file beside itself", + lambda: shadow.write_text(shadow_text.replace(shadow_colour, "[1, 0, 1]"), encoding="utf-8"), + lambda: shadow.unlink())) + for label, apply, undo in attacks: + apply() + names = sorted(o.name for o in collection.all_objects) + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + undo() + source.write_text(original, encoding="utf-8") + require(result == {"CANCELLED"} and "includes its faction's language files" in message, + f"A hull that {label} was built: {message!r}") + require(sorted(o.name for o in collection.all_objects) == names, "A refused Build changed objects") + for echoed in (ship_id, str(GAME), fixture): + require(echoed not in message, f"The refusal echoes an input ({echoed})") + print(f"PASS {number}.7 Build refuses a hull that redefines or shadows its language") + + # An author's copy of a generated zone, and an edit of a generated zone or mount, are the author's: Build refuses + # and leaves them as they are. + zone = bpy.data.objects[body] + piece = zone.copy() + piece.data = zone.data.copy() + piece.name = "my piece" + collection.objects.link(piece) + names = sorted(o.name for o in collection.all_objects) + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"CANCELLED"} and "did not make" in message, f"Build ignored a copy of a generated zone: {message!r}") + require(sorted(o.name for o in collection.all_objects) == names and bpy.data.objects.get("my piece") is piece, + "Build removed a copy of a generated zone") + mesh = piece.data + bpy.data.objects.remove(piece) + bpy.data.meshes.remove(mesh) + original_vertices = [tuple(v.co) for v in zone.data.vertices] + zone.data.vertices[0].co.z += 5.0 + zone.data.update() + names = sorted(o.name for o in collection.all_objects) + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"CANCELLED"} and "did not make" in message, f"Build ignored an edited zone: {message!r}") + require(sorted(o.name for o in collection.all_objects) == names and abs(zone.data.vertices[0].co.z - original_vertices[0][2] - 5.0) < 1e-3, + "Build discarded an edited zone") + api = sys.modules["aetheria_ships"] + require(api._retire_hull_source(collection) is False and source.is_file(), + "One edited zone, with the others still Build's, retired hull.scad") + for vertex, co in zip(zone.data.vertices, original_vertices): + vertex.co = co + zone.data.update() + mount = bpy.data.objects[roles["weapon-mount"][0]] + at = tuple(mount.location) + mount.location.x += 1.0 + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"CANCELLED"} and abs(mount.location.x - at[0] - 1.0) < 1e-6, f"Build discarded a moved mount: {message!r}") + mount.location = at + print(f"PASS {number}.8 Build refuses and keeps a copy and an edit of what it made") + + # The author replaces the zone meshes with her art and keeps Build's anchors and collider: Package ships the ship + # and retires hull.scad in that one act; Build is gone with it. + for name in list(generated(collection)): + obj = generated(collection)[name] + if obj.type == "MESH" and "aetheria.role" not in obj: + bpy.data.objects.remove(obj) + art_mesh = bpy.data.meshes.new("author hull") + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=1.0) + bm.to_mesh(art_mesh) + bm.free() + art = bpy.data.objects.new("author hull", art_mesh) + collection.objects.link(art) + art.parent = root + require(any(o.get("aetheria.role") for o in generated(collection).values()), "The scene kept no anchor of Build's") select(box) result, message = run(bpy.ops.aetheria.package_ship) report = scene.aetheria_package_report require(result == {"FINISHED"} and "deleted hull.scad" in report, f"Package did not retire the hull source: {report!r} {message!r}") require(not source.exists(), "hull.scad is still there after the author's art was packaged") + require("aetheria.hull_built" not in collection, "The record of Build's objects outlived hull.scad") require(all(echoed not in report for echoed in (ship_id, str(GAME))), "The report echoes an input") - print(f"PASS {number}.6 operator art retires hull.scad, with a report") + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"CANCELLED"} and bpy.data.objects.get("author hull") is art, f"Build ran after takeover: {message!r}") + print(f"PASS {number}.9 her art with Build's anchors kept retires hull.scad, with a report; Build then refuses") return collection +def check_poses(collection, root, runner): + """Every built anchor stands where the hull source says in Ship Root's frame, turned as it says, and the emitter and + radiator meshes are the source's meshes in that frame.""" + inverse = root.matrix_world.inverted() + for anchor in hull_source.read_anchors(runner("anchors")[1]): + obj = bpy.data.objects[anchor.id] + local = inverse @ obj.matrix_world + require(approx(tuple(local.translation), anchor.position), f"{anchor.id} stands at {tuple(local.translation)}, not {anchor.position}") + if anchor.role != "weapon-muzzle": + turn = local.to_euler().z + want = math.radians(anchor.yaw) + require(approx((math.cos(turn), math.sin(turn)), (math.cos(want), math.sin(want))), + f"{anchor.id} is turned {math.degrees(turn):.1f} degrees, not {anchor.yaw}") + if anchor.role in hull_source.MESH_ROLES: + made = sorted(tuple(round(c, 3) for c in (inverse @ obj.matrix_world @ v.co)) for v in obj.data.vertices) + wanted = sorted(tuple(round(c, 3) for c in v) for v in hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]).vertices) + require(len(made) == len(wanted) and all(approx(a, b, 2e-3) for a, b in zip(made, wanted)), + f"The mesh of {anchor.id} is not the source's mesh in Ship Root's frame") + + +def yawed_mount(scene, box, collection, root, package, source, original, runner): + """A mount the source turns 90 degrees stands, turned, where it says, and its muzzle follows it.""" + changed = original.replace('[0, Y0+3.2, H+0.6], 0, ""]', '[0, Y0+3.2, H+0.6], 90, ""]') + require(changed != original, "The tender's mount is not where the pose test turns it") + source.write_text(changed, encoding="utf-8") + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"FINISHED"}, f"Build refused a turned mount: {message!r}") + check_poses(collection, root, runner) + require(abs(bpy.data.objects["Gun.D"].rotation_euler.z - math.pi / 2) < 1e-4, "The mount is not turned 90 degrees") + source.write_text(original, encoding="utf-8") + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"FINISHED"}, f"Build refused the restored source: {message!r}") + print("PASS 1.10 a turned mount and its muzzle stand where the source puts them") + + def clear(collection): """Removes a finished ship's objects: Blender names objects once per file, and anchors are found by name.""" for obj in list(collection.all_objects if collection else ()): @@ -269,14 +422,19 @@ def main(): sys.path.insert(0, str(REPO / "tools" / "blender")) addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) import aetheria_ships + global hull_source, EXECUTABLE + hull_source = aetheria_ships.hull_source aetheria_ships._brokkr_cultlib = lambda context: PACKAGES preferences = bpy.context.preferences.addons["aetheria_ships"].preferences preferences.game_folder = str(GAME) if OPENSCAD: preferences.openscad = OPENSCAD + EXECUTABLE = preferences.openscad real = aetheria_ships.hull_source.openscad_runner def logged(executable, source, **kwargs): + kwargs.pop("on_start", None) + def on_start(pid): if PID_LOG: with open(PID_LOG, "a") as log: diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py index 62aed4168..2b71561a3 100644 --- a/tools/blender/tests/test_hull_source.py +++ b/tools/blender/tests/test_hull_source.py @@ -10,8 +10,10 @@ hull_source is loaded by path because the package __init__ imports bpy. import importlib.util import json import sys +import tempfile import unittest from pathlib import Path +from unittest import mock _spec = importlib.util.spec_from_file_location( "hull_source", Path(__file__).resolve().parents[1] / "aetheria_ships" / "hull_source.py") @@ -46,13 +48,15 @@ def brief(faction="zhestokost", donor="", length=(8, 14), triangles=(10, 100)): class Fixture: - """A hull source as the fake runner sees it: part -> (OFF, ECHO).""" + """A hull source as the fake runner sees it: part -> (OFF, ECHO). library holds the ECHO text of each faction's own + language file; the hull's own `lang` echo is the files it includes, unless hull_lang says otherwise.""" def __init__(self): + self.library = {"zhestokost": language()} + self.hull_lang = None # Body 6 wide, 10 long, 2 high (h/w 0.33, w/l 0.6); a bilateral plate on top; one gun with a muzzle nose-ward. self.parts = { "brief": ("", brief()), - "lang": ("", language()), "primary": (box(-3, 3, -5, 5, 0, 2), ""), "secondary": (box(-1, 1, -1, 1, 2, 3), ""), "anchors": ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) @@ -62,10 +66,15 @@ class Fixture: } def runner(self): - return lambda part: self.parts[part] + return lambda part: ("", self.hull_lang if self.hull_lang is not None else "".join(self.library.values())) if part == "lang" else self.parts[part] + + def read_library(self, faction): + if faction not in self.library: + raise hs.HullSourceError("no such language file") + return self.library[faction] def build(self): - return hs.build(self.runner()) + return hs.build(self.runner(), self.read_library) def failed(self): return [c.name for c in self.build().failed()] @@ -106,7 +115,7 @@ class ReadingTests(unittest.TestCase): def test_a_pirate_language_reads_with_no_body_and_no_proportion(self): pirate = hs.read_languages(language("pirate", ("primer", "weld"), body="", proportion=None, - symmetry=("asymmetric", 0.9)))["pirate"] + symmetry=("asymmetric", 0.9)))[0] self.assertEqual((pirate.body, pirate.proportion, pirate.symmetry), ("", None, ("asymmetric", 0.9))) def test_a_language_naming_an_unknown_rule_or_a_body_outside_its_zones_is_refused(self): @@ -143,7 +152,7 @@ class JudgementTests(unittest.TestCase): def test_the_language_decides_proportions_not_the_hull(self): # The same 6 x 10 x 2 body: inside Zhestokost's ranges, outside a language that wants tall narrow bodies. fixture = Fixture() - fixture.parts["lang"] = ("", language(proportion=((0.8, 1.2), (0.1, 0.3)))) + fixture.library["zhestokost"] = language(proportion=((0.8, 1.2), (0.1, 0.3))) self.assertEqual(fixture.failed(), ["the body's proportions lie inside the language's ranges"]) def test_a_body_too_tall_for_the_language_fails_proportion_and_nothing_else(self): @@ -151,6 +160,15 @@ class JudgementTests(unittest.TestCase): fixture.parts["primary"] = (box(-3, 3, -5, 5, 0, 5), "") self.assertEqual(fixture.failed(), ["the body's proportions lie inside the language's ranges"]) + def test_a_body_too_wide_for_its_length_fails_proportion_and_nothing_else(self): + fixture = Fixture() + fixture.parts["primary"] = (box(-6, 6, -5, 5, 0, 4), "") # h/w 0.33 but w/l 1.2 + self.assertEqual(fixture.failed(), ["the body's proportions lie inside the language's ranges"]) + + def test_every_zone_of_the_language_is_coloured_with_its_own_palette_entry(self): + built = Fixture().build() + self.assertEqual(built.colours, {"primary": (0.1, 0.2, 0.3), "secondary": (0.2, 0.2, 0.3)}) + def test_a_body_too_narrow_for_the_language_fails_proportion(self): fixture = Fixture() fixture.parts["primary"] = (box(-1, 1, -5, 5, 0, 1), "") @@ -163,17 +181,17 @@ class JudgementTests(unittest.TestCase): def test_a_bilateral_bound_is_met_by_exactly_that_overlap(self): fixture = Fixture() - fixture.parts["lang"] = ("", language(symmetry=("bilateral", 1.0))) + fixture.library["zhestokost"] = language(symmetry=("bilateral", 1.0)) self.assertEqual(fixture.failed(), []) def test_an_asymmetric_language_refuses_a_symmetric_hull(self): fixture = Fixture() - fixture.parts["lang"] = ("", language("zhestokost", symmetry=("asymmetric", 0.9))) + fixture.library["zhestokost"] = language("zhestokost", symmetry=("asymmetric", 0.9)) self.assertEqual(fixture.failed(), ["the top view obeys the language's asymmetric rule"]) def test_an_asymmetric_language_accepts_a_lopsided_hull(self): fixture = Fixture() - fixture.parts["lang"] = ("", language("zhestokost", symmetry=("asymmetric", 0.9))) + fixture.library["zhestokost"] = language("zhestokost", symmetry=("asymmetric", 0.9)) fixture.parts["secondary"] = (box(2, 8, -4, 4, 0, 3), "") self.assertEqual(fixture.failed(), []) @@ -244,9 +262,9 @@ class DonorTests(unittest.TestCase): def pirate(donor_proportion=((0.12, 0.35), (0.55, 1.1)), donor="rnd"): fixture = Fixture() fixture.parts["brief"] = ("", brief("pirate", donor, length=(8, 14))) - fixture.parts["lang"] = ("", language("pirate", ("primer", "weld"), body="", proportion=None, - symmetry=("asymmetric", 0.9)) - + language("rnd", ("primary", "secondary"), proportion=donor_proportion)) + fixture.library = {"pirate": language("pirate", ("primer", "weld"), body="", proportion=None, + symmetry=("asymmetric", 0.9)), + "rnd": language("rnd", ("primary", "secondary"), proportion=donor_proportion)} for key in ("primary", "secondary"): del fixture.parts[key] fixture.parts["rnd:primary"] = (box(-3, 3, -5, 5, 0, 1), "") # h/w 0.17, w/l 0.6 @@ -275,8 +293,7 @@ class DonorTests(unittest.TestCase): def test_a_pirate_hull_that_names_no_donor_is_refused(self): fixture = self.pirate(donor="") - fixture.parts["lang"] = ("", language("pirate", ("primer", "weld"), body="", proportion=None, - symmetry=("asymmetric", 0.9))) + del fixture.library["rnd"] for key in ("rnd:primary", "rnd:secondary"): del fixture.parts[key] self.assertIn(self.DONOR, fixture.failed()) @@ -284,12 +301,167 @@ class DonorTests(unittest.TestCase): def test_a_hull_whose_language_has_proportions_of_its_own_may_not_name_a_donor(self): fixture = Fixture() fixture.parts["brief"] = ("", brief("zhestokost", "rnd")) - fixture.parts["lang"] = ("", language() + language("rnd", ("primary", "secondary"))) + fixture.library["rnd"] = language("rnd", ("primary", "secondary")) fixture.parts["rnd:primary"] = (box(-3, 3, -5, 5, 0, 1), "") fixture.parts["rnd:secondary"] = (box(-1, 1, -1, 1, 1, 1.2), "") self.assertIn(self.DONOR, fixture.failed()) +class LanguageOwnershipTests(unittest.TestCase): + """The faction's language file owns its palette, proportions and symmetry rule: the hull's own `lang` echo is compared + with it and never judged against.""" + + OWN = "the hull includes its faction's language files and changes none of them" + PROPORTIONS = "the body's proportions lie inside the language's ranges" + + def redefined(self, **language_arguments): + fixture = Fixture() + fixture.hull_lang = language(**language_arguments) + return fixture + + def test_a_hull_that_includes_the_languages_unchanged_passes(self): + self.assertEqual(Fixture().failed(), []) + + def test_a_hull_that_redefines_its_palette_fails_and_is_still_coloured_from_the_file(self): + fixture = Fixture() + fixture.hull_lang = echo("lang", ["zhestokost", [["primary", [1, 0, 1]], ["secondary", [1, 0, 1]]], "primary", + [1, 0.6, 0.2], [0.5, 0.5, 0.5], [[0.25, 0.6], [0.35, 0.75]], ["bilateral", 0.97]]) + self.assertEqual(fixture.failed(), [self.OWN]) + built = fixture.build() + self.assertEqual(built.colours["primary"], built.languages["zhestokost"].colour("primary")) + self.assertNotEqual(built.colours["primary"], (1, 0, 1)) + + def test_a_hull_that_adds_a_zone_to_its_palette_fails(self): + self.assertEqual(self.redefined(zones=("primary", "secondary", "extra")).failed(), [self.OWN]) + + def test_a_hull_that_redefines_the_proportions_fails_and_is_judged_by_the_file(self): + fixture = self.redefined(proportion=((0.0, 9.0), (0.0, 9.0))) + fixture.parts["primary"] = (box(-3, 3, -5, 5, 0, 5), "") # too tall for the file's ranges + self.assertEqual(sorted(fixture.failed()), sorted([self.OWN, self.PROPORTIONS])) + + def test_a_hull_that_redefines_the_symmetry_rule_fails_and_is_judged_by_the_file(self): + fixture = self.redefined(symmetry=("asymmetric", 0.99)) + self.assertEqual(fixture.failed(), [self.OWN]) + fixture.parts["secondary"] = (box(2, 6, -1, 1, 2, 3), "") # lopsided: the file's bilateral rule refuses it + self.assertIn("the top view obeys the language's bilateral rule", fixture.failed()) + + def test_a_second_echo_of_the_language_after_the_first_fails(self): + fixture = Fixture() + fixture.hull_lang = language() + language(symmetry=("asymmetric", 0.99)) + self.assertEqual(fixture.failed(), [self.OWN]) + + def test_a_hull_that_echoes_no_language_or_another_factions_fails(self): + for text in ("", language("rnd")): + fixture = Fixture() + fixture.hull_lang = text + self.assertEqual(fixture.failed(), [self.OWN]) + + def test_a_pirate_hull_must_include_its_donors_language_too(self): + fixture = DonorTests.pirate() + fixture.hull_lang = language("pirate", ("primer", "weld"), body="", proportion=None, symmetry=("asymmetric", 0.9)) + self.assertEqual(fixture.failed(), [self.OWN]) + + def test_the_library_is_asked_for_the_faction_and_the_donor_the_brief_names(self): + asked = [] + fixture = DonorTests.pirate() + hs.build(fixture.runner(), lambda faction: asked.append(faction) or fixture.read_library(faction)) + self.assertEqual(sorted(asked), ["pirate", "rnd"]) + + +class FakeOpenScad: + """Stands in for subprocess.Popen: records each command and environment, writes `off` where -o points, and answers + with `output` and `returncode`.""" + + def __init__(self, returncode=0, off="", output=""): + self.returncode, self.off, self.output, self.calls = returncode, off, output, [] + self.pid = 4242 + + def __call__(self, command, **kwargs): + self.calls.append((command, kwargs.get("env"))) + if self.off: + Path(command[command.index("-o") + 1]).write_text(self.off, encoding="utf-8") + return self + + def communicate(self, timeout=None): + return self.output, None + + def kill(self): + pass + + +class LanguageLibraryTests(unittest.TestCase): + def test_a_faction_name_that_is_not_a_plain_word_or_has_no_file_is_refused_without_a_process(self): + with tempfile.TemporaryDirectory() as folder, mock.patch.object(hs.subprocess, "Popen") as popen: + (Path(folder) / "zhestokost.scad").write_text("", encoding="utf-8") + read = hs.language_library("openscad", Path(folder)) + for faction in ("../zhestokost", "Zhestokost", "", "nobody", "zhestokost.scad"): + with self.assertRaises(hs.HullSourceError) as caught: + read(faction) + self.assertNotIn("nobody", str(caught.exception)) + popen.assert_not_called() + + def test_the_language_is_read_from_the_factions_own_file_run_alone(self): + with tempfile.TemporaryDirectory() as folder: + library = Path(folder) + (library / "zhestokost.scad").write_text("", encoding="utf-8") + openscad = FakeOpenScad(output=language()) + with mock.patch.object(hs.subprocess, "Popen", openscad): + text = hs.language_library("openscad", library)("zhestokost") + self.assertEqual(hs.read_languages(text)[0].faction, "zhestokost") + command = openscad.calls[0][0] + self.assertEqual(command[-1], str(library / "zhestokost.scad")) + self.assertEqual(command[command.index("-D") + 1], 'part="lang"') + + +class RunnerTests(unittest.TestCase): + def run_part(self, part, openscad, **arguments): + with mock.patch.object(hs.subprocess, "Popen", openscad): + return hs.openscad_runner("scad", "hull.scad", **arguments)(part) + + def test_openscad_is_asked_for_a_full_render_on_the_manifold_backend_of_one_part(self): + openscad = FakeOpenScad() + self.run_part("primary", openscad) + command = openscad.calls[0][0] + self.assertEqual(command[0], "scad") + self.assertEqual(command[command.index("--backend") + 1], "Manifold") + self.assertEqual(command[command.index("--render") + 1], "all") + self.assertEqual(command[command.index("-D") + 1], 'part="primary"') + self.assertEqual(command[-1], "hull.scad") + + def test_the_language_folder_is_what_openscad_searches_for_includes(self): + openscad = FakeOpenScad() + self.run_part("primary", openscad, library=Path("some") / "languages") + self.assertEqual(openscad.calls[0][1]["OPENSCADPATH"], str(Path("some") / "languages")) + + def test_a_part_openscad_fails_to_make_is_refused_without_echoing_its_output(self): + with self.assertRaises(hs.HullSourceError) as caught: + self.run_part("primary", FakeOpenScad(returncode=1, output=SECRET)) + self.assertNotIn(SECRET, str(caught.exception)) + + def test_echo_parts_answer_the_echo_and_geometry_parts_the_off(self): + self.assertEqual(self.run_part("brief", FakeOpenScad(output=brief())), ("", brief())) + self.assertEqual(self.run_part("primary", FakeOpenScad(off=box(0, 1, 0, 1, 0, 1), output="log")), + (box(0, 1, 0, 1, 0, 1), "log")) + + def test_each_process_is_reported_to_on_start(self): + started = [] + self.run_part("primary", FakeOpenScad(), on_start=started.append) + self.assertEqual(started, [4242]) + + +class FingerprintTests(unittest.TestCase): + def test_equal_values_give_equal_digests_and_a_change_gives_another(self): + base = hs.fingerprint("a", (1.0, 2.5), [[0.0, 1.0, 2.0]], 3) + self.assertEqual(base, hs.fingerprint("a", (1.0, 2.5), [[0.0, 1.0, 2.0]], 3)) + for other in (("b", (1.0, 2.5), [[0.0, 1.0, 2.0]], 3), ("a", (1.0, 2.501), [[0.0, 1.0, 2.0]], 3), + ("a", (1.0, 2.5), [[0.0, 1.0, 2.0]], 4), ("a", (1.0, 2.5), [[0.0, 1.0], [2.0]], 3)): + self.assertNotEqual(base, hs.fingerprint(*other)) + + def test_float_noise_below_five_decimals_and_a_negative_zero_do_not_change_it(self): + self.assertEqual(hs.fingerprint((1.0, 0.0)), hs.fingerprint((1.0 + 1e-8, -0.0))) + self.assertEqual(hs.fingerprint((-1e-9,)), hs.fingerprint((0.0,))) + + class RefusalTests(unittest.TestCase): def test_a_source_that_includes_no_language_for_its_faction_is_refused(self): fixture = Fixture() @@ -297,12 +469,19 @@ class RefusalTests(unittest.TestCase): with self.assertRaises(hs.HullSourceError): fixture.build() - def test_a_named_donor_whose_language_the_source_does_not_include_is_refused(self): + def test_a_named_donor_that_has_no_language_file_is_refused(self): fixture = Fixture() fixture.parts["brief"] = ("", brief("zhestokost", "rnd")) with self.assertRaises(hs.HullSourceError): fixture.build() + def test_a_language_file_that_echoes_another_faction_or_not_exactly_one_language_is_refused(self): + for text in (language("rnd"), language() + language(), ""): + fixture = Fixture() + fixture.library["zhestokost"] = text + with self.assertRaises(hs.HullSourceError): + fixture.build() + def test_anchors_that_repeat_an_id_or_name_an_unknown_role_are_refused_without_echoing_them(self): for anchors in (echo("anchor", [SECRET, "weapon-mount", [0, 0, 0], 0, ""]) * 2, echo("anchor", [SECRET, "map-icon", [0, 0, 0], 0, ""])): @@ -312,6 +491,31 @@ class RefusalTests(unittest.TestCase): fixture.build() self.assertNotIn(SECRET, str(caught.exception)) + def test_a_name_that_is_not_a_string_is_refused_wherever_the_source_gives_one(self): + def refused(fixture): + with self.assertRaises(hs.HullSourceError): + fixture.build() + + for index in range(3): # faction, donor, role + fixture = Fixture() + raw = ["zhestokost", "", "tender", [8, 14], [10, 100], ["a read"]] + raw[index] = 7 + fixture.parts["brief"] = ("", echo("brief", raw)) + refused(fixture) + fixture = Fixture() + fixture.parts["brief"] = ("", echo("brief", ["zhestokost", "", "tender", [8, 14], [10, 100], [7]])) + refused(fixture) + for anchor in ([7, "weapon-mount", [0, 0, 3], 0, ""], ["Gun.A", 7, [0, 0, 3], 0, ""], + ["Gun.A", "weapon-mount", [0, 0, 3], 0, 7]): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", anchor)) + refused(fixture) + for raw in ([7, [["primary", [1, 1, 1]]], "primary", [1, 1, 1], [1, 1, 1], [], ["bilateral", 1]], + ["zhestokost", [[7, [1, 1, 1]]], "primary", [1, 1, 1], [1, 1, 1], [], ["bilateral", 1]], + ["zhestokost", [["primary", [1, 1, 1]]], 7, [1, 1, 1], [1, 1, 1], [], ["bilateral", 1]]): + with self.assertRaises(hs.HullSourceError): + hs.read_languages(echo("lang", raw)) + def test_a_malformed_anchor_is_refused_without_echoing_it(self): fixture = Fixture() fixture.parts["anchors"] = ("", echo("anchor", [SECRET, "weapon-mount", [0, 0], 0, ""]))