From 763fa0987f5975bf29401a91d51aa0a62f69e20c Mon Sep 17 00:00:00 2001 From: soul Date: Sun, 18 Oct 2026 21:57:47 +0200 Subject: [PATCH] hull_source: reads a hull.scad through OpenSCAD and judges it against its faction's form language One language file per faction (Zhestokost, Rossum & Douglas, Pirate) owns the shape kit, proportions, symmetry rule and palette; the Zhestokost palette follows the lore page (ruling zhestokost-language-lore-text). The two probe hulls are ported as fixtures. Checks: zones, emitter and radiator meshes, donor, body proportions, top-view mirror overlap, length, triangle budget, muzzles nose-ward. Fixture-text tests need no OpenSCAD. Co-Authored-By: Claude Sonnet 5.5 --- .../aetheria_ships/factions/lowpoly.scad | 14 + .../aetheria_ships/factions/pirate.scad | 43 +++ .../blender/aetheria_ships/factions/rnd.scad | 30 ++ .../aetheria_ships/factions/zhestokost.scad | 60 +++ tools/blender/aetheria_ships/hull_source.py | 344 ++++++++++++++++++ .../tests/fixtures/hulls/pi-fighter/hull.scad | 50 +++ .../fixtures/hulls/zh-ammo-tender/hull.scad | 49 +++ tools/blender/tests/test_hull_source.py | 304 ++++++++++++++++ 8 files changed, 894 insertions(+) create mode 100644 tools/blender/aetheria_ships/factions/lowpoly.scad create mode 100644 tools/blender/aetheria_ships/factions/pirate.scad create mode 100644 tools/blender/aetheria_ships/factions/rnd.scad create mode 100644 tools/blender/aetheria_ships/factions/zhestokost.scad create mode 100644 tools/blender/aetheria_ships/hull_source.py create mode 100644 tools/blender/tests/fixtures/hulls/pi-fighter/hull.scad create mode 100644 tools/blender/tests/fixtures/hulls/zh-ammo-tender/hull.scad create mode 100644 tools/blender/tests/test_hull_source.py diff --git a/tools/blender/aetheria_ships/factions/lowpoly.scad b/tools/blender/aetheria_ships/factions/lowpoly.scad new file mode 100644 index 000000000..9979483a0 --- /dev/null +++ b/tools/blender/aetheria_ships/factions/lowpoly.scad @@ -0,0 +1,14 @@ +// Shared low-poly primitives (any faction). Frame: Blender Ship Root, nose -Y, starboard -X, up +Z. +// cbox: a box with one chamfer segment on every edge (the operator's one-segment-bevel bar, as geometry). +module cbox(s, c=0.2, center=true) { + t = center ? [0,0,0] : s/2; + translate(t) hull() { + cube([s.x, s.y-2*c, s.z-2*c], center=true); + cube([s.x-2*c, s.y, s.z-2*c], center=true); + cube([s.x-2*c, s.y-2*c, s.z], center=true); + } +} +// tube along +Y (nose is -Y, so a forward barrel uses rotate 180 or negative length) +module tube(r, l, fn=8) { rotate([-90,0,0]) cylinder(r=r, h=l, $fn=fn); } +// a straight strut between two points +module strut(a, b, r=0.08, fn=6) { hull() { translate(a) sphere(r, $fn=fn); translate(b) sphere(r, $fn=fn); } } diff --git a/tools/blender/aetheria_ships/factions/pirate.scad b/tools/blender/aetheria_ships/factions/pirate.scad new file mode 100644 index 000000000..8705869a1 --- /dev/null +++ b/tools/blender/aetheria_ships/factions/pirate.scad @@ -0,0 +1,43 @@ +// Pirate Coalition form language: the one owner of this faction's additions kit, symmetry rule and palette. Source: Faction Flavor > Pirate Coalition > Visual Identity: "An identifiable +// donor hull with asymmetrical additions, cut-down modules, adapted hardpoints, exposed cable routes, and bolted +// salvage plates. Each major addition has a plausible mounting and supply path." +// A Pirate hull = one donor-language body (another faction's language, named in the hull's brief and judged by its +// proportions) + these additions. This language draws no body and has no proportions of its own. +include +// Bolted salvage plate: a slightly tilted slab with proud bolt heads. +module pi_plate(w, l, t=0.12, tilt=4) { + rotate([tilt, -tilt*0.6, 0]) { cube([w, l, t], center=true); + for (x=[-w/2+0.15, w/2-0.15], y=[-l/2+0.15, l/2-0.15]) translate([x, y, t/2]) cylinder(r=0.07, h=0.06, $fn=6); } +} +// Exposed cable run: a chain of short segments sagging between clamp points. +module pi_cable(pts, r=0.06) { for (i=[0:len(pts)-2]) strut(pts[i], pts[i+1], r, 5); } +// Weld bead / adapter collar where an addition meets the donor. +module pi_collar(r, h=0.2) { cylinder(r=r, h=h, center=true, $fn=8); } +// Adapted hardpoint: a crude saddle (two plates + braces) that carries something the donor never had. +module pi_saddle(w, l, h) { + translate([0,0,h/2]) cube([w, l, 0.15], center=true); + for (x=[-w/2+0.1, w/2-0.1]) translate([x, 0, h/4]) cube([0.12, l*0.8, h/2], center=true); + strut([-w/2, -l/2, 0], [w/2, l/2, h], 0.05); strut([w/2, -l/2, 0], [-w/2, l/2, h], 0.05); +} +// Replacement drive: an oversize bell on a braced cradle, not matching the donor's flush engines. +module pi_drive(r, l) { + rotate([-90,0,0]) { cylinder(r1=r*0.55, r2=r, h=l*0.45, $fn=8); translate([0,0,-l*0.55]) cylinder(r=r*0.6, h=l*0.55, $fn=8); } +} +// Oversized industrial gun (a mass driver pulled off a mining rig): long box receiver, single heavy barrel. +module pi_big_gun(len, cal=0.2) { + cbox([0.9, len*0.35, 0.7], 0.08); + translate([0, -len*0.17, 0.05]) rotate([0,0,180]) tube(cal, len*0.65, 8); + translate([0, -len*0.82, 0.05]) rotate([0,0,180]) tube(cal*1.6, 0.35, 8); +} +// Bolted-on sensor pod: one sleek piece from a better ship, on a strut. +module pi_sensor_pod(l=1.4, r=0.3) { scale([1, l/(2*r), 1]) sphere(r, $fn=10); } + +PI_ZONES = [["primer", [0.48, 0.27, 0.22]], // primer-red salvage plates + ["weld", [0.70, 0.68, 0.62]], // welded additions: guns, drives, cables + ["accent", [0.10, 0.62, 0.60]], // the crew's own colour + ["recess", [0.08, 0.08, 0.09]]]; +PI_GLOW = [0.55, 0.85, 1.0]; +PI_RADIATOR = [0.70, 0.68, 0.62]; +// No body zone and no proportions: the donor's. The additions must make the top view visibly lopsided. +PI_LANG = ["pirate", PI_ZONES, "", PI_GLOW, PI_RADIATOR, [], ["asymmetric", 0.9]]; +if (part == "lang") echo(lang = PI_LANG); diff --git a/tools/blender/aetheria_ships/factions/rnd.scad b/tools/blender/aetheria_ships/factions/rnd.scad new file mode 100644 index 000000000..ae7da7241 --- /dev/null +++ b/tools/blender/aetheria_ships/factions/rnd.scad @@ -0,0 +1,30 @@ +// Rossum & Douglas form language: "the flying wedge". Source: Faction Flavor > Rossum & Douglas > Visual Identity. +// The one owner of this faction's shape kit, proportions, symmetry rule and palette. It also serves as a donor language: +// a Pirate hull builds on a stolen R&D wedge (Bench 3 "Jumble Sale"). +include +// Broad shallow trapezoid narrowing to a blunt nose (-Y), wide rear face (+Y), flat dorsal plane, +// bevelled perimeter, thicker centre section. One idea, no flourishes. +module rd_wedge(L, w_rear, w_nose, h_edge, h_centre) { + hull() { + translate([0, L/2-0.3, 0]) cube([w_rear, 0.6, h_edge], center=true); // rear face + translate([0, -L/2+0.3, 0]) cube([w_nose, 0.6, h_edge*0.8], center=true); // blunt nose + translate([0, L*0.05, 0]) cube([w_rear*0.45, L*0.7, h_centre], center=true); // thick centre + } +} +// Flush rear engine bank: shallow rectangular recesses across the rear face. +module rd_engine_bank(w, h, n=3) { + for (i=[0:n-1]) translate([(i-(n-1)/2)*(w/n), 0, 0]) cube([w/n*0.7, 0.5, h], center=true); +} +// Recessed window strip and identical hatches: barely interrupt the planes. +module rd_window(w=1.2) { cube([w, 0.35, 0.18], center=true); } +module rd_hatch() { cube([0.9, 1.1, 0.06], center=true); } + + +RD_ZONES = [["primary", [0.72, 0.74, 0.76]], // the wedge + ["secondary", [0.40, 0.47, 0.56]], // hatches, panels + ["accent", [0.90, 0.89, 0.84]], // stripes + ["recess", [0.10, 0.12, 0.18]]]; // windows, engine bank +RD_GLOW = [1.0, 0.75, 0.3]; +RD_RADIATOR = [0.40, 0.47, 0.56]; +RD_LANG = ["rnd", RD_ZONES, "primary", RD_GLOW, RD_RADIATOR, [[0.12, 0.35], [0.55, 1.1]], ["bilateral", 0.97]]; +if (part == "lang") echo(lang = RD_LANG); diff --git a/tools/blender/aetheria_ships/factions/zhestokost.scad b/tools/blender/aetheria_ships/factions/zhestokost.scad new file mode 100644 index 000000000..c00139dd8 --- /dev/null +++ b/tools/blender/aetheria_ships/factions/zhestokost.scad @@ -0,0 +1,60 @@ +// Zhestokost form language: the one owner of this faction's shape kit, proportions, symmetry rule and palette. +// Canon. Operator ruling zhestokost-language-lore-text: Zhestokost is industrial and brutalist, "the dream of the +// eternal Soviet, a society that has achieved total and unassailable permaculture via a carefully organized and +// brutally practical (self-policing) state". Form follows the lore page ("Faction Flavor and Visual Identity" > +// Zhestokost): low broad stepped masses, deep seams, charcoal, iron grey, dull oxide red. The operator's faction sheet +// (Asset Sources/Zhestokost.png) lends the handling boom with hanging magazines as vocabulary, not its palette. +// A hull composes these modules; nothing here places itself. +include +ZH_CH = 0.22; // chamfer: heavy, square, one segment +// A stepped mass: tiers shrink upward and pull in from both ends. "Low, broad ... stepped rectangular masses." +module zh_stepped(L, W, H, tiers=3, pull=0.12) { + for (i=[0:tiers-1]) let(k=i/tiers) + translate([0, 0, H*k + H/tiers/2]) cbox([W*(1-pull*i*1.6), L*(1-pull*i), H/tiers + 0.02], ZH_CH); +} +// Armour plate standing proud of a face, leaving a deep seam (the seam is the gap to the next plate). +module zh_plate(w, l, t=0.3) { cbox([w, l, t], 0.08); } +// Recessed machinery: a dark box set into a mass (subtract the pocket in the hull, then place this inside). +module zh_recess(w, l, d) { cube([w, l, d], center=true); } +// Ammunition magazine: square cassette with ribbed loading face and a hanger lug on top. +module zh_cassette(w=1.2, l=1.6, h=2.0) { + cbox([w, l, h], 0.12); + for (z=[-h*0.3, 0, h*0.3]) translate([0, -l/2-0.04, z]) cube([w*0.8, 0.12, 0.18], center=true); + translate([0, 0, h/2+0.2]) cube([0.3, 0.6, 0.4], center=true); +} +// Handling boom: square box beam with cross-members; magazines hang from it. +module zh_boom(len, w=0.9, h=0.7) { + cbox([w, len, h], 0.1); + for (y=[-len/2+0.6:1.6:len/2-0.4]) translate([0, y, -h/2-0.1]) cube([w+0.4, 0.25, 0.25], center=true); +} +// Towing point: a thick eye on a block. +module zh_tow_lug() { cbox([0.6, 0.6, 0.4], 0.08); translate([0,0,0.45]) rotate([0,90,0]) difference() { cylinder(r=0.38, h=0.25, center=true, $fn=8); cylinder(r=0.18, h=1, center=true, $fn=8); } } +// Ballistic mount: square base, slab mantlet, N thick barrels with a box muzzle brake. Barrels point -Y (nose). +module zh_gun(n=2, cal=0.22, len=3.0, base=1.6) { + cbox([base, base, 0.5], 0.12); + translate([0, 0, 0.55]) cbox([base*0.85, base*0.7, 0.7], 0.12); + for (i=[0:n-1]) translate([(i-(n-1)/2)*cal*3, -base*0.3, 0.6]) { + rotate([0,0,180]) tube(cal, len, 8); + translate([0, -len, 0]) cbox([cal*3, cal*3.5, cal*3], 0.04); + } +} +// Drive block: a flat rear face with square nozzles in a grid (recessed: emitters sit at the nozzle mouths). +module zh_drive_block(w, h, d, nx=2, nz=1, nozzle=1.0) { + difference() { + cbox([w, d, h], ZH_CH); + for (i=[0:nx-1], j=[0:nz-1]) translate([(i-(nx-1)/2)*(w/nx), d/2, (j-(nz-1)/2)*(h/nz)]) cube([nozzle, 0.8, nozzle], center=true); + } +} + + +// Palette zones. Value contrast carries the read at 48 px on dark space: the body is iron grey, the plates and seams +// are charcoal, the oxide red is the only hue. Zones become livery mask channels. +ZH_ZONES = [["primary", [0.42, 0.43, 0.45]], // iron grey: the stepped mass + ["secondary", [0.20, 0.20, 0.22]], // charcoal: armour plates, booms, guns, command block + ["accent", [0.55, 0.22, 0.14]], // dull oxide red: magazines, markings + ["recess", [0.08, 0.08, 0.09]]]; // recessed machinery +ZH_GLOW = [1.0, 0.62, 0.25]; +ZH_RADIATOR = [0.50, 0.51, 0.52]; +// [faction, zones, body zone, glow, radiator, [height/width range, width/length range], symmetry rule] +ZH_LANG = ["zhestokost", ZH_ZONES, "primary", ZH_GLOW, ZH_RADIATOR, [[0.25, 0.6], [0.35, 0.75]], ["bilateral", 0.97]]; +if (part == "lang") echo(lang = ZH_LANG); diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py new file mode 100644 index 000000000..f66c27810 --- /dev/null +++ b/tools/blender/aetheria_ships/hull_source.py @@ -0,0 +1,344 @@ +"""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: + + 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) + 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 + +Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. build() returns a HullBuild; the caller refuses on any failed +check. Messages and check names are fixed text: nothing a hull source says is echoed back. +""" + +import json +import math +import os +import re +import subprocess +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Optional + +FACTIONS_DIR = Path(__file__).with_name("factions") +HULL_FILE = "hull.scad" +OPENSCAD_TIMEOUT = 180 # seconds, per part +SILHOUETTE_CELL = 0.25 # metres, the top-view raster the symmetry check compares +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 +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. +Runner = Callable[[str], "tuple[str, str]"] + + +class HullSourceError(ValueError): + """The hull source could not be read. The message is fixed text.""" + + +@dataclass(frozen=True) +class Mesh: + vertices: tuple + triangles: tuple + + def bounds(self): + """((min x, y, z), (max x, y, z)).""" + columns = list(zip(*self.vertices)) + return tuple(min(c) for c in columns), tuple(max(c) for c in columns) + + +@dataclass(frozen=True) +class Language: + faction: str + zones: tuple # ((name, (r, g, b)), ...) + body: str # the zone whose proportions the language judges; "" for a language with no body of its own + glow: tuple + radiator: tuple + proportion: Optional[tuple] # ((h/w min, max), (w/l min, max)); None for a language that takes its donor's + symmetry: tuple # ("bilateral", minimum mirror overlap) or ("asymmetric", maximum mirror overlap) + + def zone_names(self): + return [name for name, _ in self.zones] + + def colour(self, zone): + return dict(self.zones)[zone] + + +@dataclass(frozen=True) +class Brief: + faction: str + donor: str + role: str + length: tuple + triangles: tuple + reads: tuple + + +@dataclass(frozen=True) +class Anchor: + id: str + role: str + position: tuple + yaw: float + parent: str + + +@dataclass(frozen=True) +class Check: + name: str + ok: bool + detail: str = "" + + +@dataclass +class HullBuild: + brief: Brief + languages: dict # faction -> Language + zones: dict # zone key ("primary", "rnd:primary") -> Mesh + colours: dict # zone key -> (r, g, b) + anchors: list + anchor_meshes: dict # anchor id -> Mesh + glow: tuple + radiator: tuple + body_zone: str # the zone key the collider is made from + checks: list = field(default_factory=list) + + def failed(self): + return [check for check in self.checks if not check.ok] + + +def parse_off(text): + """(vertices, triangles) of an OFF file, faces fanned into triangles. An empty or absent text is an empty mesh.""" + lines = [line.split() for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")] + if not lines or lines[0][0] != "OFF": + return Mesh((), ()) + try: + header = lines[1] if len(lines[0]) == 1 else lines[0][1:] + vertex_count, face_count = int(header[0]), int(header[1]) + first = 2 if len(lines[0]) == 1 else 1 + vertices = tuple(tuple(float(v) for v in lines[first + i][:3]) for i in range(vertex_count)) + triangles = [] + for row in lines[first + vertex_count:first + vertex_count + face_count]: + ring = [int(v) for v in row[1:1 + int(row[0])]] + triangles += [(ring[0], ring[i], ring[i + 1]) for i in range(1, len(ring) - 1)] + if any(not 0 <= v < vertex_count for tri in triangles for v in tri): + raise ValueError + except (ValueError, IndexError): + raise HullSourceError("The hull source made geometry that is not a readable OFF file") from None + return Mesh(vertices, tuple(triangles)) + + +def parse_echoes(text, name): + """The values of every 'ECHO: = ' line. OpenSCAD prints JSON-compatible values.""" + values = [] + for key, raw in ECHO_LINE.findall(text): + if key != name: + continue + try: + values.append(json.loads(raw)) + except ValueError: + raise HullSourceError(f"The hull source echoed a {name} that is not plain numbers, strings and lists") from None + return values + + +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") + return tuple(value) + + +def _number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _text(value): + if not isinstance(value, str): + raise HullSourceError("The hull source echoed a name that is not a string") + return value + + +def read_brief(text): + (raw,) = _exactly_one(parse_echoes(text, "brief"), "brief") + if not isinstance(raw, list) or len(raw) != 6 or not isinstance(raw[5], list): + raise HullSourceError("The hull source's brief has the wrong shape") + return Brief(_text(raw[0]), _text(raw[1]), _text(raw[2]), _vector(raw[3], 2), _vector(raw[4], 2), + tuple(_text(r) for r in raw[5])) + + +def _proportion(raw): + if raw == []: + return None + if not isinstance(raw, list) or len(raw) != 2: + raise HullSourceError("A faction language has the wrong shape") + return _vector(raw[0], 2), _vector(raw[1], 2) + + +def read_languages(text): + 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") + zones = tuple((_text(z[0]), _vector(z[1], 3)) for z in raw[1] if isinstance(z, list) and len(z) == 2) + if len(zones) != len(raw[1]): + raise HullSourceError("A faction language has the wrong shape") + proportion = _proportion(raw[5]) + symmetry = _vector(raw[6], 2, numbers=False) + if symmetry[0] not in ("bilateral", "asymmetric") or not _number(symmetry[1]): + raise HullSourceError("A faction language names a symmetry rule it does not have") + language = Language(_text(raw[0]), zones, _text(raw[2]), _vector(raw[3], 3), _vector(raw[4], 3), proportion, + 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 + return languages + + +def read_anchors(text): + anchors = [] + for raw in parse_echoes(text, "anchor"): + if not isinstance(raw, list) or len(raw) != 5 or not _number(raw[3]): + raise HullSourceError("An anchor has the wrong shape") + anchors.append(Anchor(_text(raw[0]), _text(raw[1]), _vector(raw[2], 3), float(raw[3]), _text(raw[4]))) + return anchors + + +def _exactly_one(values, what): + if len(values) != 1: + raise HullSourceError(f"The hull source must echo exactly one {what}") + return values + + +def mirror_overlap(triangles_xy, cell=SILHOUETTE_CELL): + """Intersection over union of the top-view silhouette with its reflection across x = 0. The silhouette is every raster + cell whose centre a triangle covers (a feature thinner than a cell may not show).""" + cells = set() + for (ax, ay), (bx, by), (cx, cy) in triangles_xy: + det = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy) + if abs(det) < 1e-12: + continue + for i in range(math.floor(min(ax, bx, cx) / cell), math.floor(max(ax, bx, cx) / cell) + 1): + px = (i + 0.5) * cell + for j in range(math.floor(min(ay, by, cy) / cell), math.floor(max(ay, by, cy) / cell) + 1): + py = (j + 0.5) * cell + u = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / det + v = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / det + if u >= 0 and v >= 0 and u + v <= 1: + cells.add((i, j)) + mirrored = {(-i - 1, j) for i, j in cells} + union = len(cells | mirrored) + return len(cells & mirrored) / union if union else 1.0 + + +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.""" + _, 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") + 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 ())}) + zones = {key: parse_off(runner(key)[0]) for key in zone_keys} + _, text = runner("anchors") + anchors = read_anchors(text) + ids = [a.id for a in anchors] + if len(set(ids)) != len(ids) or any(a.role not in ANCHOR_ROLES for a in anchors): + raise HullSourceError("The hull source's anchors repeat an id or name a role a hull source does not make") + 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) + return result + + +def _checks(hull, own, judge): + brief, checks = hull.brief, [] + empty = [key for key, mesh in hull.zones.items() if not mesh.triangles] + checks.append(Check("every zone of the language has geometry", not empty, f"{len(empty)} empty")) + missing = [a.id for a in hull.anchors if a.role in MESH_ROLES and not hull.anchor_meshes[a.id].triangles] + checks.append(Check("every emitter and radiator anchor has a mesh", not missing, f"{len(missing)} without")) + checks.append(Check("a donor is named exactly when the language has no proportions of its own", + bool(brief.donor) == (own.proportion is None), "")) + body = hull.zones[hull.body_zone] if hull.body_zone in hull.zones else Mesh((), ()) + if body.triangles and judge.proportion: + low, high = body.bounds() + width, length, height = (high[0] - low[0]), (high[1] - low[1]), (high[2] - low[2]) + ratios = (height / width if width else float("inf"), width / length if length else float("inf")) + (hw_lo, hw_hi), (wl_lo, wl_hi) = judge.proportion + checks.append(Check("the body's proportions lie inside the language's ranges", + hw_lo <= ratios[0] <= hw_hi and wl_lo <= ratios[1] <= wl_hi, + f"h/w {ratios[0]:.2f}, w/l {ratios[1]:.2f}")) + else: + checks.append(Check("the body's proportions lie inside the language's ranges", False, "no body to judge")) + every = [m for m in list(hull.zones.values()) + list(hull.anchor_meshes.values()) if m.triangles] + if every: + overlap = mirror_overlap([t for m in every for t in _triangles_xy(m)]) + rule, bound = own.symmetry + checks.append(Check(f"the top view obeys the language's {rule} rule", + overlap >= bound if rule == "bilateral" else overlap <= bound, f"mirror overlap {overlap:.2f}")) + ys = [v[1] for m in every for v in m.vertices] + length = max(ys) - min(ys) + checks.append(Check("the length lies inside the brief's range", brief.length[0] <= length <= brief.length[1], + f"{length:.1f} m")) + else: + checks.append(Check("the top view obeys the language's symmetry rule", False, "no geometry")) + checks.append(Check("the length lies inside the brief's range", False, "no geometry")) + triangles = sum(len(m.triangles) for m in every) + checks.append(Check("the triangle count lies inside the brief's budget", + brief.triangles[0] <= triangles <= brief.triangles[1], f"{triangles}")) + by_id = {a.id: a for a in hull.anchors} + unmuzzled = [a.id for a in hull.anchors if a.role == "weapon-mount" + and not any(m.role == "weapon-muzzle" and m.parent == a.id for m in hull.anchors)] + forward = [m.id for m in hull.anchors if m.role == "weapon-muzzle" and m.parent in by_id + and by_id[m.parent].role == "weapon-mount" and m.position[1] >= by_id[m.parent].position[1]] + orphans = [m.id for m in hull.anchors if m.role == "weapon-muzzle" + and (m.parent not in by_id or by_id[m.parent].role != "weapon-mount")] + checks.append(Check("every weapon-mount has a muzzle nose-ward of it and no muzzle is orphaned", + not (unmuzzled or forward or orphans), + f"{len(unmuzzled)} without a muzzle, {len(forward)} not nose-ward, {len(orphans)} orphaned")) + return checks + + +def openscad_runner(executable, source, library=FACTIONS_DIR, on_start=None): + """A Runner that runs OpenSCAD (Manifold backend, full render) on source, one process at a time. on_start(pid) is + called with each process's id. OPENSCADPATH is the language folder, so a hull source includes .""" + env = dict(os.environ, OPENSCADPATH=str(library)) + + def run(part): + with tempfile.TemporaryDirectory() as folder: + target = Path(folder) / ("part.echo" if part in ECHO_PARTS else "part.off") + command = [str(executable), "--backend", "Manifold", "--render", "all", "-D", f'part="{part}"', + "-o", str(target), str(source)] + try: + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env) + except OSError: + raise HullSourceError("OpenSCAD could not be started") from None + if on_start: + on_start(process.pid) + try: + output, _ = process.communicate(timeout=OPENSCAD_TIMEOUT) + except subprocess.TimeoutExpired: + process.kill() + process.communicate() + raise HullSourceError("OpenSCAD did not finish a part in time") from None + if process.returncode != 0: + raise HullSourceError("OpenSCAD refused a part of the hull source") + written = target.read_text(encoding="utf-8", errors="replace") if target.exists() else "" + return ("", written + output) if part in ECHO_PARTS else (written, output) + + return run diff --git a/tools/blender/tests/fixtures/hulls/pi-fighter/hull.scad b/tools/blender/tests/fixtures/hulls/pi-fighter/hull.scad new file mode 100644 index 000000000..3af7a1812 --- /dev/null +++ b/tools/blender/tests/fixtures/hulls/pi-fighter/hull.scad @@ -0,0 +1,50 @@ +// Pirate Coalition fighter "Markdown" on a stolen Rossum & Douglas wedge. An agent-built hull source: the donor body +// comes from the Rossum & Douglas language, every addition from the Pirate language. +// part = lang | brief | anchors | rnd: | primer | weld | accent | recess | emit: +include +include +part = "rnd:primary"; + +HULL_FACTION = "pirate"; +HULL_DONOR = "rnd"; +HULL_ROLE = "fighter"; +HULL_LENGTH = [9, 16]; +HULL_TRIANGLES = [300, 6000]; +HULL_READS = ["the stolen R&D wedge is still recognisable (flat dorsal plane, blunt nose, flush engine face)", + "one oversized gun out of proportion to the hull, on an adapted mount", + "a replacement drive that does not match", "bolted salvage plates, an exposed cable run, one stolen sensor pod", + "asymmetric"]; +if (part == "brief") echo(brief = [HULL_FACTION, HULL_DONOR, HULL_ROLE, HULL_LENGTH, HULL_TRIANGLES, HULL_READS]); + +L = 11; WR = 8; WN = 2.4; +module cut() { translate([-WR/2+0.4, L/2-0.6, 0]) rotate([0,0,35]) cube([3.2, 2.6, 3], center=true); } +module wedge() { difference() { rd_wedge(L, WR, WN, 0.55, 1.5); cut(); translate([0, L/2, 0]) rd_engine_bank(5.4, 0.4, 3); translate([0, -L/2+2.2, 0.75]) rd_window(1.4); } } +module stripe() { translate([1.1, 0.5, 0.75]) cube([0.9, L*0.55, 0.04], center=true); } +module donor_hatches() { for (y=[-1.2, 1.4]) translate([-1.4, y, 0.75]) rd_hatch(); } +module gun() { translate([2.3, -0.8, 0.45]) { pi_saddle(1.2, 2.4, 0.5); translate([0, 0, 0.9]) pi_big_gun(9.0, 0.18); } } +module drive() { translate([-2.5, L/2-0.2, 0.15]) { pi_drive(1.05, 2.6); + for (a=[[0.9,-1.4,0.2],[-0.9,-1.4,0.2],[0,-1.4,0.9]]) strut([0,0,0], a, 0.07); } } +module patch() { translate([-WR/2+1.25, L/2-1.25, 0.2]) rotate([0,0,35]) rotate([0,90,0]) pi_plate(0.7, 2.8, 0.12, 0); } +module plates() { translate([1.0, -L/2+1.9, 0.62]) pi_plate(1.4, 1.2, 0.12, 6); translate([-0.6, 2.4, 0.8]) pi_plate(1.8, 1.4, 0.12, -5); } +module welded_engine() { translate([1.8, L/2+0.05, 0]) cube([1.6, 0.12, 0.4], center=true); } +module cables() { pi_cable([[2.0, 0.6, 1.0], [1.0, 1.6, 0.9], [-0.6, 2.8, 0.95], [-1.6, 3.6, 0.85], [-2.3, 4.0, 0.9]]); } +module pod() { translate([-1.4, -2.6, 1.3]) pi_sensor_pod(1.5, 0.32); strut([-1.4, -2.6, 0.7], [-1.4, -2.6, 1.1], 0.07); } +module crew_slash() { translate([-0.2, -1.6, 0.78]) rotate([0,0,-38]) cube([0.55, 4.4, 0.04], center=true); } + +if (part == "rnd:primary") wedge(); +if (part == "rnd:secondary") donor_hatches(); +if (part == "rnd:accent") stripe(); +if (part == "rnd:recess") { translate([0, -L/2+2.2, 0.72]) rd_window(1.3); translate([0, L/2-0.25, 0]) cube([1.6, 0.05, 0.36], center=true); } +if (part == "primer") { patch(); plates(); welded_engine(); } +if (part == "weld") { gun(); drive(); cables(); } +if (part == "accent") { crew_slash(); pod(); } +if (part == "recess") translate([-2.5, L/2-0.2, 0.15]) pi_collar(1.15, 0.15); +if (part == "emit:Th.Main") translate([-2.5, L/2-0.2+1.17, 0.15]) rotate([90,0,0]) cylinder(r=0.95, h=0.05, center=true, $fn=8); +if (part == "emit:Th.L") translate([0, L/2-0.22, 0]) cube([1.2, 0.05, 0.32], center=true); +// Ids are HullData mount ids: the gameplay layout addresses these by name only. +if (part == "anchors") { + echo(anchor=["Gun.P", "weapon-mount", [2.3, -0.8, 1.35], 0, ""]); + echo(anchor=["Gun.P.muzzle", "weapon-muzzle", [2.3, -0.8-0.17*9.0-0.65*9.0-0.4, 1.4], 0, "Gun.P"]); + echo(anchor=["Th.Main", "thruster-emitter", [-2.5, L/2-0.2+1.17, 0.15], 180, ""]); + echo(anchor=["Th.L", "thruster-emitter", [0, L/2-0.22, 0], 180, ""]); +} diff --git a/tools/blender/tests/fixtures/hulls/zh-ammo-tender/hull.scad b/tools/blender/tests/fixtures/hulls/zh-ammo-tender/hull.scad new file mode 100644 index 000000000..dcd20ec00 --- /dev/null +++ b/tools/blender/tests/fixtures/hulls/zh-ammo-tender/hull.scad @@ -0,0 +1,49 @@ +// Zhestokost ammunition tender "Podvoz". An agent-built hull source: composes the Zhestokost language only. +// part = lang | brief | anchors | primary | secondary | accent | recess | emit: | rad: +// Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. Anchor yaw: 0 nose, 90 port, 180 aft, 270 starboard. +include +part = "primary"; + +HULL_FACTION = "zhestokost"; +HULL_DONOR = ""; +HULL_ROLE = "tender"; +HULL_LENGTH = [18, 28]; +HULL_TRIANGLES = [300, 6000]; +HULL_READS = ["ammunition magazines carried where a rearming ship can see and reach them", + "a handling boom that brings magazines forward", "towing points", + "one defensive ballistic mount, not a warship battery", "low, broad, heavy, slow"]; +if (part == "brief") echo(brief = [HULL_FACTION, HULL_DONOR, HULL_ROLE, HULL_LENGTH, HULL_TRIANGLES, HULL_READS]); + +L = 15; W = 10; H = 4.2; Y0 = 3; // main mass centred at y=+3 (nose is -Y) +module pockets() { for (s=[-1,1], y=[-1, 4]) translate([s*W/2, Y0+y, 1.3]) cube([1.2, 2.6, 1.4], center=true); } +module body() { difference() { translate([0, Y0, 0]) zh_stepped(L, W, H, 3, 0.10); pockets(); } } +module plates() { for (s=[-1,1], i=[0:3]) translate([s*(W/2+0.05), Y0-5.4+i*3.6, 0.6]) rotate([0,0,90]) rotate([90,0,0]) zh_plate(3.2, 1.0, 0.3); } +module band() { for (s=[-1,1], i=[0:3]) translate([s*(W/2+0.22), Y0-5.4+i*3.6, 0.6]) cube([0.04, 3.2, 0.3], center=true); } +module booms() { for (s=[-1,1]) translate([s*2.6, -5.0, H-0.3]) { zh_boom(13); translate([0, 5.6, -0.9]) cbox([1.4, 1.4, 1.6], 0.12); } } +module magazines() { for (s=[-1,1], i=[0:3]) translate([s*3.75, -10.4+i*1.9, H-1.7]) zh_cassette(1.2, 1.5, 2.0); } +module arms() { for (s=[-1,1], i=[0:3]) translate([s*3.2, -10.4+i*1.9, H-0.45]) cube([1.6, 0.3, 0.3], center=true); } +module bridge() { translate([0, Y0+5.6, H]) { cbox([4.4, 2.6, 1.4], ZH_CH); translate([0, 0.3, 1.2]) cbox([2.8, 1.8, 1.0], ZH_CH); + translate([0, -1.32, 0.35]) cube([3.2, 0.06, 0.3], center=true); } } +module lugs() { for (s=[-1,1], y=[Y0-L/2+0.8, Y0+L/2-1.0]) translate([s*(W/2-1.6), y, H/3+0.2]) zh_tow_lug(); } +module drive() { translate([0, Y0+L/2+0.6, 1.3]) zh_drive_block(6.0, 2.2, 1.6, 2, 1, 1.3); } +module gun() { translate([0, Y0+3.2, H]) zh_gun(2, 0.2, 2.6, 1.6); } +module rad(s) { translate([s*(W/2+1.35), Y0+5.2, 2.0]) cube([2.5, 2.2, 0.12], center=true); } +module recess_fill() { for (s=[-1,1], y=[-1, 4]) translate([s*(W/2-0.55), Y0+y, 1.3]) cube([0.1, 2.5, 1.3], center=true); } + +if (part == "primary") { body(); drive(); } +if (part == "secondary") { plates(); booms(); arms(); lugs(); gun(); bridge(); } +if (part == "accent") { magazines(); band(); } +if (part == "recess") recess_fill(); +if (part == "rad:Ra.L") rad(1); +if (part == "rad:Ra.R") rad(-1); +if (part == "emit:Th.L") translate([ 1.5, Y0+L/2+1.05, 1.3]) cube([1.2, 0.05, 1.2], center=true); +if (part == "emit:Th.R") translate([-1.5, Y0+L/2+1.05, 1.3]) cube([1.2, 0.05, 1.2], center=true); +// Ids are HullData mount ids: the gameplay layout addresses these by name only. +if (part == "anchors") { + echo(anchor=["Gun.D", "weapon-mount", [0, Y0+3.2, H+0.6], 0, ""]); + echo(anchor=["Gun.D.muzzle", "weapon-muzzle", [0, Y0+3.2-0.48-2.6-0.3, H+1.15], 0, "Gun.D"]); + echo(anchor=["Th.L", "thruster-emitter", [ 1.5, Y0+L/2+1.05, 1.3], 180, ""]); + echo(anchor=["Th.R", "thruster-emitter", [-1.5, Y0+L/2+1.05, 1.3], 180, ""]); + echo(anchor=["Ra.L", "radiator-mesh", [ W/2+1.35, Y0+5.2, 2.0], 0, ""]); + echo(anchor=["Ra.R", "radiator-mesh", [-W/2-1.35, Y0+5.2, 2.0], 0, ""]); +} diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py new file mode 100644 index 000000000..5f66bebe0 --- /dev/null +++ b/tools/blender/tests/test_hull_source.py @@ -0,0 +1,304 @@ +"""Blender-free tests for aetheria_ships/hull_source.py, which reads a hull.scad through OpenSCAD and judges it against its +faction's form language. A fake runner answers each part with fixture OFF and ECHO text, so no OpenSCAD runs here; the +real OpenSCAD and the real language files are exercised by smoke_hull_source.py. + + python -m unittest discover -s tools/blender/tests -p "test_hull_source.py" + +hull_source is loaded by path because the package __init__ imports bpy. +""" + +import importlib.util +import json +import sys +import unittest +from pathlib import Path + +_spec = importlib.util.spec_from_file_location( + "hull_source", Path(__file__).resolve().parents[1] / "aetheria_ships" / "hull_source.py") +hs = importlib.util.module_from_spec(_spec) +sys.modules["hull_source"] = hs +_spec.loader.exec_module(hs) + +SECRET = "SECRET-NAME-7" # a value a hull source supplies and no refusal may echo + + +def box(x0, x1, y0, y1, z0, z1): + """An OFF text for an axis-aligned box: 8 vertices, 6 quads (12 triangles once fanned).""" + v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)] + quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + rows = ["OFF", "8 6 0"] + [f"{x} {y} {z}" for x, y, z in v] + [f"4 {a} {b} {c} {d}" for a, b, c, d in quads] + return "\n".join(rows) + + +def echo(name, value): + return f"ECHO: {name} = {json.dumps(value)}\n" + + +def language(faction="zhestokost", zones=("primary", "secondary"), body="primary", proportion=((0.25, 0.6), (0.35, 0.75)), + symmetry=("bilateral", 0.97)): + palette = [[z, [0.1 * (i + 1), 0.2, 0.3]] for i, z in enumerate(zones)] + return echo("lang", [faction, palette, body, [1, 0.6, 0.2], [0.5, 0.5, 0.5], [list(p) for p in proportion] if proportion + else [], list(symmetry)]) + + +def brief(faction="zhestokost", donor="", length=(8, 14), triangles=(10, 100)): + return echo("brief", [faction, donor, "tender", list(length), list(triangles), ["a read"]]) + + +class Fixture: + """A hull source as the fake runner sees it: part -> (OFF, ECHO).""" + + def __init__(self): + # 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, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], 180, ""])), + "emit:Th.A": (box(0.5, 1.5, 5, 5.1, 0.5, 1.5), ""), + } + + def runner(self): + return lambda part: self.parts[part] + + def build(self): + return hs.build(self.runner()) + + def failed(self): + return [c.name for c in self.build().failed()] + + +class ReadingTests(unittest.TestCase): + def test_off_fans_polygons_into_triangles(self): + mesh = hs.parse_off(box(0, 1, 0, 1, 0, 1)) + self.assertEqual((len(mesh.vertices), len(mesh.triangles)), (8, 12)) + self.assertEqual(mesh.bounds(), ((0, 0, 0), (1, 1, 1))) + + def test_off_accepts_a_header_with_counts_on_the_first_line_and_skips_comments(self): + mesh = hs.parse_off("OFF 3 1 0\n# c\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n") + self.assertEqual(mesh.triangles, ((0, 1, 2),)) + + def test_nothing_is_an_empty_mesh_and_a_broken_file_is_refused_without_echoing_it(self): + self.assertEqual(hs.parse_off("").triangles, ()) + with self.assertRaises(hs.HullSourceError) as caught: + hs.parse_off(f"OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 9 {SECRET}\n") + self.assertNotIn(SECRET, str(caught.exception)) + + def test_echoes_are_read_by_name_and_only_plain_values_are_accepted(self): + text = echo("anchor", ["a", 1]) + echo("other", [2]) + echo("anchor", ["b", 2.5e-05]) + self.assertEqual(hs.parse_echoes(text, "anchor"), [["a", 1], ["b", 2.5e-05]]) + with self.assertRaises(hs.HullSourceError) as caught: + hs.parse_echoes(f"ECHO: anchor = [{SECRET}, undef]\n", "anchor") + self.assertNotIn(SECRET, str(caught.exception)) + + def test_a_brief_is_exactly_one_echo_of_six_fields(self): + self.assertEqual(hs.read_brief(brief()).faction, "zhestokost") + for text in ("", brief() + brief(), echo("brief", ["x"])): + with self.assertRaises(hs.HullSourceError): + hs.read_brief(text) + + 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"] + 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): + with self.assertRaises(hs.HullSourceError): + hs.read_languages(language(symmetry=("mostly", 0.5))) + with self.assertRaises(hs.HullSourceError): + hs.read_languages(language(body="keel")) + + +class MirrorOverlapTests(unittest.TestCase): + @staticmethod + def top(text): + mesh = hs.parse_off(text) + return hs._triangles_xy(mesh) + + def test_a_centred_box_overlaps_its_reflection_completely(self): + self.assertEqual(hs.mirror_overlap(self.top(box(-2, 2, 0, 4, 0, 1))), 1.0) + + def test_a_box_on_one_side_does_not_overlap_it_at_all(self): + self.assertEqual(hs.mirror_overlap(self.top(box(1, 3, 0, 4, 0, 1))), 0.0) + + def test_a_box_straddling_the_axis_unevenly_overlaps_by_the_shared_part(self): + # x in [-1, 3]: the reflection covers [-3, 1]; shared [-1, 1] = 2 of a union 6 wide + self.assertAlmostEqual(hs.mirror_overlap(self.top(box(-1, 3, 0, 4, 0, 1))), 2 / 6, places=2) + + +class JudgementTests(unittest.TestCase): + def test_a_hull_that_keeps_every_rule_passes_every_check(self): + self.assertEqual(Fixture().failed(), []) + + 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)))) + 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): + fixture = Fixture() + 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_narrow_for_the_language_fails_proportion(self): + fixture = Fixture() + fixture.parts["primary"] = (box(-1, 1, -5, 5, 0, 1), "") + self.assertIn("the body's proportions lie inside the language's ranges", fixture.failed()) + + def test_a_bilateral_language_refuses_a_lopsided_hull(self): + fixture = Fixture() + fixture.parts["secondary"] = (box(2, 6, -1, 1, 2, 3), "") + self.assertEqual(fixture.failed(), ["the top view obeys the language's bilateral rule"]) + + def test_an_asymmetric_language_refuses_a_symmetric_hull(self): + fixture = Fixture() + fixture.parts["lang"] = ("", 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.parts["secondary"] = (box(2, 8, -4, 4, 0, 3), "") + self.assertEqual(fixture.failed(), []) + + def test_a_zone_the_language_names_must_have_geometry(self): + fixture = Fixture() + fixture.parts["secondary"] = ("", "") + self.assertEqual(fixture.failed(), ["every zone of the language has geometry"]) + + def test_the_triangle_budget_is_a_range_with_two_ends(self): + for budget in ((10, 20), (1000, 2000)): + fixture = Fixture() + fixture.parts["brief"] = ("", brief(triangles=budget)) + self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"], budget) + + def test_the_length_is_a_range_with_two_ends(self): + for length in ((1, 5), (30, 40)): + fixture = Fixture() + fixture.parts["brief"] = ("", brief(length=length)) + self.assertEqual(fixture.failed(), ["the length lies inside the brief's range"], length) + + MUZZLE = "every weapon-mount has a muzzle nose-ward of it and no muzzle is orphaned" + + def test_a_muzzle_aft_of_its_mount_is_refused(self): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, 1, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], 180, ""])) + self.assertEqual(fixture.failed(), [self.MUZZLE]) + + def test_a_muzzle_level_with_its_mount_is_not_nose_ward(self): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [1, 0, 3], 0, "Gun.A"])) + self.assertEqual(fixture.failed(), [self.MUZZLE]) + + def test_a_mount_without_a_muzzle_and_a_muzzle_without_a_mount_are_refused(self): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""])) + self.assertEqual(fixture.failed(), [self.MUZZLE]) + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"])) + self.assertEqual(fixture.failed(), [self.MUZZLE]) + + def test_an_emitter_with_no_mesh_is_refused(self): + fixture = Fixture() + fixture.parts["emit:Th.A"] = ("", "") + self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + + def test_the_collider_zone_is_the_languages_body(self): + self.assertEqual(Fixture().build().body_zone, "primary") + + +class DonorTests(unittest.TestCase): + """A Pirate hull: the Pirate language has no body and no proportions, so the donor's decide.""" + + @staticmethod + 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)) + 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 + fixture.parts["rnd:secondary"] = (box(-1, 1, -1, 1, 1, 1.2), "") + fixture.parts["primer"] = (box(2, 4, -4, -2, 0, 1), "") + fixture.parts["weld"] = (box(2, 6, 0, 4, 0, 1), "") + return fixture + + def test_the_donors_proportions_judge_the_body(self): + fixture = self.pirate() + self.assertEqual(fixture.build().body_zone, "rnd:primary") + self.assertEqual(fixture.failed(), []) + self.assertEqual(self.pirate(donor_proportion=((0.5, 0.9), (0.55, 1.1))).failed(), + ["the body's proportions lie inside the language's ranges"]) + + def test_the_donors_zones_are_required_and_coloured_from_the_donor(self): + fixture = self.pirate() + fixture.parts["rnd:secondary"] = ("", "") + self.assertEqual(fixture.failed(), ["every zone of the language has geometry"]) + self.assertEqual(fixture.build().colours["rnd:primary"], fixture.build().languages["rnd"].colour("primary")) + + DONOR = "a donor is named exactly when the language has no proportions of its own" + + 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))) + for key in ("rnd:primary", "rnd:secondary"): + del fixture.parts[key] + self.assertIn(self.DONOR, fixture.failed()) + + 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.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 RefusalTests(unittest.TestCase): + def test_a_source_that_includes_no_language_for_its_faction_is_refused(self): + fixture = Fixture() + fixture.parts["brief"] = ("", brief("nobody")) + 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, ""])): + fixture = Fixture() + fixture.parts["anchors"] = ("", anchors) + with self.assertRaises(hs.HullSourceError) as caught: + fixture.build() + self.assertNotIn(SECRET, str(caught.exception)) + + def test_a_malformed_anchor_is_refused_without_echoing_it(self): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", [SECRET, "weapon-mount", [0, 0], 0, ""])) + with self.assertRaises(hs.HullSourceError) as caught: + fixture.build() + self.assertNotIn(SECRET, str(caught.exception)) + + def test_check_names_and_details_carry_no_hull_supplied_text(self): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", [SECRET, "weapon-mount", [0, 0, 3], 0, ""])) + fixture.parts["emit:Th.A"] = ("", "") + for check in fixture.build().checks: + self.assertNotIn(SECRET, check.name + check.detail) + + def test_the_module_writes_no_json_and_starts_no_second_process(self): + source = (Path(hs.__file__)).read_text(encoding="utf-8") + for forbidden in ("json.dump", "ThreadPool", "concurrent.futures", "multiprocessing"): + self.assertNotIn(forbidden, source) + self.assertEqual(source.count("subprocess.Popen"), 1) + + +if __name__ == "__main__": + unittest.main()