From eaf063a1203cde9b18ca0d3490500e0d278df6e4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 11:23:23 +0100 Subject: [PATCH 01/10] kitbash core: sheet, the cage and creases of a shell description Sheet and sheet(document): a loft of rings as quads wound by a stated rule, crease runs along ring and column edges, a rim weight, a mirror in x. SheetTests pin the grid, the mirror, the runs and every refusal. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 161 ++++++++++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 120 ++++++++++++++++++ 2 files changed, 281 insertions(+) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 6e3b6ef..d6156c9 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -25,6 +25,10 @@ finds where a section line meets a half-plane, resample fills a section's points says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy around them. +An armor shell is a loft, not a kit part: sheet turns a shell description (rings of points, crease runs along ring +and column edges, a rim weight, a mirror in x) into a quad cage wound by a stated rule and the creases a subdivision +surface keeps on it. brokkr_kitbash.shell is the bpy around it. + A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane. @@ -973,6 +977,163 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list return kept +# --- shells: a loft of rings and its creases ------------------------------------------------------------------- + +SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring +SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner +MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it +SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip") + + +class Sheet(NamedTuple): + """A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (every face a quad, + shaded smooth, no sharp edge) and what a subdivision surface creases. creases is an (E, 2) array of vertex index + pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. Vertex + i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored).""" + V: np.ndarray + faces: np.ndarray + counts: np.ndarray + smooth: np.ndarray + sharp: np.ndarray + creases: np.ndarray + weights: np.ndarray + corners: np.ndarray + corner_weights: np.ndarray + rings: int + points: int + + +def _index(value: Any, where: str, least: int, most: int) -> int: + if isinstance(value, bool) or not isinstance(value, int) or not least <= value <= most: + raise KitError(f"{where} must be a whole number from {least} to {most}, not {value!r}") + return value + + +def _weight(value: Any, where: str) -> float: + if not finite(value) or not 0.0 <= value <= 1.0: + raise KitError(f"{where} must be a number from 0 to 1, not {value!r}") + return float(value) + + +def sheet(document: Any) -> Sheet: + """The cage of a shell description {rings, closed, mirror, creases, rim, flip}. + + rings: 2 to 64 rings of 2 to 64 [x, y, z] points, equal counts. Quad (i, j) is P[i][j], P[i][j+1], P[i+1][j+1], + P[i+1][j], so its normal (P[i][j+1] - P[i][j]) x (P[i+1][j] - P[i][j]) faces out: seen from outside, a ring's + points run left to right and the rings run upward. flip reverses every face. closed joins each ring's last + point to its first. mirror: each ring is authored from its point 0 on x = 0 toward +x and becomes its mirrored + points in reverse, then itself (2C - 1 points); a crease names authored indices and lands on both halves. + + creases: {ring, from, to, weight} creases ring's edges from point `from` to point `to` (on a closed ring `to` + may be the count: the edge back to point 0); {column, from, to, weight} a column's edges from ring `from` to + ring `to`; {point: [ring, point], weight} one vertex. rim is the weight of every boundary edge no run names. + An edge has one weight: two runs that give it different ones are refused.""" + _keys(document, "sheet", ("rings",), SHEET_KEYS) + flags = {} + for key in ("closed", "mirror", "flip"): + flags[key] = document.get(key, False) + if not isinstance(flags[key], bool): + raise KitError(f"sheet.{key} must be true or false, not {flags[key]!r}") + closed, mirror, flip = flags["closed"], flags["mirror"], flags["flip"] + if mirror and closed: + raise KitError("sheet.mirror with sheet.closed: a mirrored ring runs from -x to +x and has two ends; state one of them") + rim = _weight(document.get("rim", 1.0), "sheet.rim") + rings = document["rings"] + if not isinstance(rings, list) or not 2 <= len(rings) <= SHEET_LIMIT: + raise KitError(f"sheet.rings must be 2 to {SHEET_LIMIT} rings, not {len(rings) if isinstance(rings, list) else rings!r}") + for i, ring in enumerate(rings): + if not isinstance(ring, list) or not 2 <= len(ring) <= SHEET_LIMIT: + raise KitError(f"sheet.rings[{i}] must be 2 to {SHEET_LIMIT} points, not {len(ring) if isinstance(ring, list) else ring!r}") + if len(ring) != len(rings[0]): + raise KitError(f"sheet.rings[{i}] has {len(ring)} points and sheet.rings[0] has {len(rings[0])}: a loft's rings have equal counts") + for j, point in enumerate(ring): + if not isinstance(point, list) or len(point) != 3 or not all(finite(v) for v in point): + raise KitError(f"sheet.rings[{i}][{j}] must be three finite numbers [x, y, z]") + P = np.array(rings, dtype=np.float64) + R, C = P.shape[:2] + if mirror: + for i in range(R): + if abs(P[i, 0, 0]) > MIRROR_EPS: + raise KitError(f"sheet.rings[{i}][0] has x = {P[i, 0, 0]:.6g}: a mirrored ring starts on x = 0") + for j in range(C): + if P[i, j, 0] < -MIRROR_EPS: + raise KitError(f"sheet.rings[{i}][{j}] has x = {P[i, j, 0]:.6g}: a mirrored ring is authored on the +x side") + P[:, 0, 0] = 0.0 + P = np.concatenate([P[:, :0:-1] * (-1.0, 1.0, 1.0), P], axis=1) + N = P.shape[1] # points in a ring as built + wrap = N if closed else N - 1 # quads, and ring edges, around a ring + columns = (lambda j: (C - 1 - j, C - 1 + j) if j else (C - 1,)) if mirror else (lambda j: (j,)) + vertex = lambda i, j: i * N + j % N # noqa: E731 + quads = np.array([[vertex(i, j), vertex(i, j + 1), vertex(i + 1, j + 1), vertex(i + 1, j)] for i in range(R - 1) for j in range(wrap)], dtype=np.int32) + V = P.reshape(-1, 3) + corners = V[quads] + areas = 0.5 * (np.linalg.norm(np.cross(corners[:, 1] - corners[:, 0], corners[:, 3] - corners[:, 0]), axis=1) + + np.linalg.norm(np.cross(corners[:, 3] - corners[:, 2], corners[:, 1] - corners[:, 2]), axis=1)) + if areas.min() < SHEET_AREA: + worst = int(areas.argmin()) + raise KitError(f"sheet: the quad between rings {worst // wrap} and {worst // wrap + 1} at point {worst % wrap} (as built) has area {areas[worst]:.3g} m2, " + f"under {SHEET_AREA:g}: a collapsed corner. Move its points apart") + if flip: + quads = quads[:, ::-1] + + edges, verts = {}, {} # (low, high) or vertex -> (weight, the run that stated it) + + def state(table, key, weight, where): + if key in table and table[key][0] != weight: + raise KitError(f"{where} gives an edge weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: an edge has one weight" if table is edges else + f"{where} gives a point weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: a point has one weight") + table.setdefault(key, (weight, where)) + + def edge(a, b): + return (min(a, b), max(a, b)) + + creases = document.get("creases", []) + if not isinstance(creases, list): + raise KitError("sheet.creases must be an array") + for k, run in enumerate(creases): + where = f"sheet.creases[{k}]" + if isinstance(run, dict) and "point" in run: + _keys(run, where, ("point", "weight")) + at = run["point"] + if not isinstance(at, list) or len(at) != 2: + raise KitError(f"{where}.point must be [ring, point]") + i, j = _index(at[0], f"{where}.point[0]", 0, R - 1), _index(at[1], f"{where}.point[1]", 0, C - 1) + weight = _weight(run["weight"], f"{where}.weight") + for column in columns(j): + state(verts, vertex(i, column), weight, where) + continue + if not isinstance(run, dict) or ("ring" in run) == ("column" in run): + raise KitError(f"{where} must be {{ring, from, to, weight}}, {{column, from, to, weight}} or {{point, weight}}") + along_ring = "ring" in run + _keys(run, where, ("ring" if along_ring else "column", "from", "to", "weight")) + weight = _weight(run["weight"], f"{where}.weight") + if along_ring: + i = _index(run["ring"], f"{where}.ring", 0, R - 1) + first, last = _index(run["from"], f"{where}.from", 0, C - 1), _index(run["to"], f"{where}.to", 0, C if closed else C - 1) + else: + j = _index(run["column"], f"{where}.column", 0, C - 1) + first, last = _index(run["from"], f"{where}.from", 0, R - 1), _index(run["to"], f"{where}.to", 0, R - 1) + if first >= last: + raise KitError(f"{where}: from {first} must be under to {last}") + for step in range(first, last): + if along_ring: + for a, b in zip(columns(step), columns(step + 1)) if step or not mirror else ((C - 1, C - 2), (C - 1, C)): + state(edges, edge(vertex(i, a), vertex(i, b)), weight, where) + else: + for column in columns(j): + state(edges, edge(vertex(step, column), vertex(step + 1, column)), weight, where) + boundary = [edge(vertex(i, j), vertex(i, j + 1)) for i in (0, R - 1) for j in range(wrap)] + if not closed: + boundary += [edge(vertex(i, j), vertex(i + 1, j)) for j in (0, N - 1) for i in range(R - 1)] + for key in boundary: + edges.setdefault(key, (rim, "sheet.rim")) + kept = sorted((key, weight) for key, (weight, _) in edges.items() if weight > 0) + pinned = sorted((key, weight) for key, (weight, _) in verts.items() if weight > 0) + return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool), + sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), + corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) + + # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c03845a..1606308 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1439,6 +1439,126 @@ class StructureTests(unittest.TestCase): self.assertEqual((len(core.joined([]).V), len(core.joined([]).counts)), (0, 0)) +class SheetTests(unittest.TestCase): + """core.sheet: the cage and creases of a shell description. Exact arithmetic: each assertion is the built value + and names the mutant it kills.""" + + @staticmethod + def rings(count=3, points=4, x0=0.0): + """Rings upward in z, points toward +x, bowed toward -y: by the winding rule their outside is -y.""" + return [[[x0 + 0.2 * j, -0.3 + 0.05 * j * j, 0.25 * i] for j in range(points)] for i in range(count)] + + @staticmethod + def normals(built): + V = built.V[built.faces.reshape(-1, 4)] + return np.cross(V[:, 1] - V[:, 0], V[:, 3] - V[:, 0]) + + @staticmethod + def weights(built) -> dict: + return {tuple(pair): weight for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} + + def test_a_grid_of_quads_wound_by_the_rule(self): + """sheet-grid. S2 (winding reversed): every quad's normal faces the known outside, -y; flip turns all.""" + built = core.sheet({"rings": self.rings(3, 4)}) + self.assertEqual((built.rings, built.points, len(built.V), len(built.counts), set(built.counts.tolist())), (3, 4, 12, 6, {4})) + self.assertEqual(built.faces[:4].tolist(), [0, 1, 5, 4]) # P[0][0], P[0][1], P[1][1], P[1][0] + self.assertTrue((self.normals(built)[:, 1] < 0).all()) + self.assertTrue(built.smooth.all() and len(built.sharp) == 0) + flipped = core.sheet({"rings": self.rings(3, 4), "flip": True}) + self.assertTrue((self.normals(flipped)[:, 1] > 0).all()) + self.assertEqual(flipped.faces[:4].tolist(), [4, 5, 1, 0]) + ring = [[math.cos(a), math.sin(a)] for a in (0.0, 2.0, 4.0)] # counter-clockwise from above, rings upward: outward + tube = core.sheet({"rings": [[[x, y, z] for x, y in ring] for z in (0.0, 1.0, 2.0)], "closed": True}) + self.assertEqual((tube.points, len(tube.counts)), (3, 6)) + centres = tube.V[tube.faces.reshape(-1, 4)].mean(axis=1) + self.assertTrue((np.einsum("ij,ij->i", self.normals(tube)[:, :2], centres[:, :2]) > 0).all()) + self.assertEqual(sorted(self.weights(tube)), [(0, 1), (0, 2), (1, 2), (6, 7), (6, 8), (7, 8)]) # a closed loft's rim: its two end rings + + def test_a_mirrored_sheet_is_symmetric(self): + """sheet-mirror. S3 (the mirrored half not reversed): the ring runs from -x to +x through point 0, vertex for + vertex the mirror of itself, and every quad faces the same outside. S10 (creases on one half).""" + built = core.sheet({"rings": self.rings(3, 3), "mirror": True, "rim": 0.0, "creases": [ + {"ring": 1, "from": 0, "to": 2, "weight": 0.75}, {"column": 1, "from": 0, "to": 2, "weight": 0.5}, {"point": [2, 2], "weight": 0.25}, + {"point": [1, 0], "weight": 1.0}]}) + self.assertEqual((built.rings, built.points, len(built.V)), (3, 5, 15)) + P = built.V.reshape(3, 5, 3) + self.assertEqual(P[:, :, 0].tolist(), [[-0.4, -0.2, 0.0, 0.2, 0.4]] * 3) + np.testing.assert_array_equal(P[:, ::-1] * (-1.0, 1.0, 1.0), P) + self.assertTrue((self.normals(built)[:, 1] < 0).all()) + quads = {tuple(q) for q in built.faces.reshape(-1, 4).tolist()} + across = lambda v: v // 5 * 5 + 4 - v % 5 # noqa: E731 + self.assertEqual({tuple(across(v) for v in (q[1], q[0], q[3], q[2])) for q in quads}, quads) # mirrored and rewound, the same faces + self.assertEqual(self.weights(built), {(5, 6): 0.75, (6, 7): 0.75, (7, 8): 0.75, (8, 9): 0.75, # ring 1, joined across point 0 + (1, 6): 0.5, (6, 11): 0.5, (3, 8): 0.5, (8, 13): 0.5}) # column 1, on both halves + self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([7, 10, 14], [1.0, 0.25, 0.25])) + + def test_runs_map_to_edges_and_the_rim_takes_the_rest(self): + """sheet-creases. S4 (rim ignored): every boundary edge no run names carries rim. S9 (a second run wins).""" + built = core.sheet({"rings": self.rings(3, 4), "rim": 0.4, "creases": [ + {"ring": 1, "from": 1, "to": 3, "weight": 1.0}, {"column": 2, "from": 0, "to": 1, "weight": 0.6}, {"ring": 0, "from": 0, "to": 1, "weight": 0.0}, + {"ring": 2, "from": 2, "to": 3, "weight": 0.9}, {"point": [0, 3], "weight": 0.7}]}) + rim = {(1, 2), (2, 3), (8, 9), (9, 10), (0, 4), (4, 8), (3, 7), (7, 11)} # the boundary less (0, 1), stated 0, and (10, 11), stated 0.9 + self.assertEqual(self.weights(built), {**{e: 0.4 for e in rim}, (5, 6): 1.0, (6, 7): 1.0, (2, 6): 0.6, (10, 11): 0.9}) + self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([3], [0.7])) + self.assertEqual(len(core.sheet({"rings": self.rings(3, 4), "rim": 0.0}).creases), 0) + self.assertEqual(set(core.sheet({"rings": self.rings(3, 4)}).weights.tolist()), {1.0}) + ring = [[math.cos(a), math.sin(a), 0.0] for a in (0.0, 1.5, 3.0, 4.5)] + tube = core.sheet({"rings": [[[x, y, z] for x, y, _ in ring] for z in (0.0, 1.0, 2.0)], "closed": True, "rim": 0.0, + "creases": [{"ring": 1, "from": 2, "to": 4, "weight": 1.0}]}) + self.assertEqual(self.weights(tube), {(6, 7): 1.0, (4, 7): 1.0}) # points 2-3, and 3 back to 0 + same = {"rings": self.rings(3, 4), "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 0.5}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]} + self.assertEqual(self.weights(core.sheet({**same, "rim": 0.0})), {(4, 5): 0.5, (5, 6): 0.5, (6, 7): 0.5}) + same["creases"][1]["weight"] = 0.6 + with self.assertRaisesRegex(core.KitError, r"sheet\.creases\[1\] gives an edge weight 0\.6 that sheet\.creases\[0\] gives 0\.5"): + core.sheet(same) + with self.assertRaisesRegex(core.KitError, r"sheet\.creases\[1\] gives a point weight 1 that sheet\.creases\[0\] gives 0\.5"): + core.sheet({"rings": self.rings(), "creases": [{"point": [0, 0], "weight": 0.5}, {"point": [0, 0], "weight": 1.0}]}) + + def test_refusals_name_the_field_and_index(self): + """sheet-refusals.""" + good = self.rings(3, 4) + bad_ring, short, nan, collapsed = copy.deepcopy(good), copy.deepcopy(good), copy.deepcopy(good), copy.deepcopy(good) + bad_ring[2] = bad_ring[2][:3] + short[1][2] = [0.0, 1.0] + nan[1][2][0] = math.nan + collapsed[1][1] = collapsed[1][2] = collapsed[0][1] = list(collapsed[0][2]) + off, behind = self.rings(3, 3, 0.01), self.rings(3, 3) + behind[1][2][0] = -0.2 + run = lambda **keys: {"rings": good, "creases": [keys]} # noqa: E731 + cases = [ + ([], "sheet must be an object"), ({}, "sheet lacks 'rings'"), ({"rings": good, "ring": 1}, "sheet has no key 'ring'"), + ({"rings": good[:1]}, r"sheet\.rings must be 2 to 64 rings, not 1"), ({"rings": [good[0]] * 65}, r"2 to 64 rings, not 65"), + ({"rings": [[[0, 0, 0]], [[0, 0, 1]]]}, r"sheet\.rings\[0\] must be 2 to 64 points, not 1"), + ({"rings": [[[float(j), 0.0, float(i)] for j in range(65)] for i in range(2)]}, r"sheet\.rings\[0\] must be 2 to 64 points, not 65"), + ({"rings": bad_ring}, r"sheet\.rings\[2\] has 3 points and sheet\.rings\[0\] has 4"), + ({"rings": short}, r"sheet\.rings\[1\]\[2\] must be three finite numbers"), ({"rings": nan}, r"sheet\.rings\[1\]\[2\] must be three finite"), + ({"rings": collapsed}, r"the quad between rings 0 and 1 at point 1 \(as built\) has area 0 m2"), + ({"rings": off, "mirror": True}, r"sheet\.rings\[0\]\[0\] has x = 0\.01: a mirrored ring starts on x = 0"), + ({"rings": behind, "mirror": True}, r"sheet\.rings\[1\]\[2\] has x = -0\.2: a mirrored ring is authored on the \+x side"), + ({"rings": self.rings(3, 3), "mirror": True, "closed": True}, r"sheet\.mirror with sheet\.closed"), + ({"rings": good, "closed": 1}, r"sheet\.closed must be true or false"), ({"rings": good, "rim": 1.5}, r"sheet\.rim must be a number from 0 to 1"), + ({"rings": good, "rim": math.inf}, r"sheet\.rim must be"), ({"rings": good, "creases": {}}, r"sheet\.creases must be an array"), + (run(ring=3, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.ring must be a whole number from 0 to 2, not 3"), + (run(ring=0, **{"from": 0, "to": 4}, weight=1), r"sheet\.creases\[0\]\.to must be a whole number from 0 to 3, not 4"), + (run(column=4, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.column must be a whole number from 0 to 3"), + (run(column=0, **{"from": 0, "to": 3}, weight=1), r"sheet\.creases\[0\]\.to must be a whole number from 0 to 2"), + (run(ring=0, **{"from": 2, "to": 2}, weight=1), r"sheet\.creases\[0\]: from 2 must be under to 2"), + (run(ring=0, **{"from": 0, "to": 1}, weight=1.01), r"sheet\.creases\[0\]\.weight must be a number from 0 to 1"), + (run(ring=0, **{"from": 0, "to": 1}), r"sheet\.creases\[0\] lacks 'weight'"), + (run(ring=0, **{"from": 0.0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.from must be a whole number"), + (run(ring=0, column=0, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\] must be \{ring, from, to, weight\}"), + (run(weight=1), r"sheet\.creases\[0\] must be \{ring"), (run(point=[0, 4], weight=1), r"sheet\.creases\[0\]\.point\[1\] must be a whole number from 0 to 3"), + (run(point=[0], weight=1), r"sheet\.creases\[0\]\.point must be \[ring, point\]"), (run(point=[0, 0], weight=1, ring=0), r"sheet\.creases\[0\] has no key 'ring'"), + ] + for document, message in cases: + with self.assertRaisesRegex(core.KitError, message, msg=message): + core.sheet(document) + closed = {"rings": [[[math.cos(a), math.sin(a), z] for a in (0.0, 2.0, 4.0)] for z in (0.0, 1.0)], "closed": True} + core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 3, "weight": 1}]}) # a closed ring's run may end at the count + with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"): + core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]}) + + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"] From 1510bac6cf1f815224171909ed6f68c24f884b41 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 11:36:24 +0100 Subject: [PATCH 02/10] brokkr_kitbash.shell: a faceted, hollow armor shell from a loft of rings shell writes the cage core.sheet builds, its crease_edge and crease_vert, Kit Subsurf (creases, corners preserved) and Kit Solidify (even, rim), and kit_shell, the request. On a shell it rewrites the mesh in place under its cutters, ribs and Booleans. It evaluates nothing. The action row, the host and ownership tests, and tests/live/kitbash_faceted.py with its result: crisp 52 deg on the creased column against 5.8 elsewhere. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 81 +++- .../brokkr_kitbash/brokkr_actions.json | 57 +++ .../blender/tests/live/kitbash_faceted.py | 383 ++++++++++++++++++ .../tests/live/kitbash_faceted.result.json | 166 ++++++++ surfaces/blender/tests/test_kitbash.py | 37 +- 5 files changed, 721 insertions(+), 3 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_faceted.py create mode 100644 surfaces/blender/tests/live/kitbash_faceted.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 32edca1..95204fb 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -43,6 +43,12 @@ a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact. +shell makes the cage that cut and ribs work on: a loft of rings with crease runs (core.sheet) under a Kit Subsurf +and a Kit Solidify. kit_shell on the object is the request, and it owns the cage mesh as kit_params owns a part's: +shell is the one writer of the mesh, its crease attributes and those two modifiers, and calling it again on the +object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell +evaluates nothing: Blender's own update after the action evaluates the plate once. + Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here @@ -79,6 +85,9 @@ BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates RIBS_LIMIT = 64 # planes in one ribs LONGERONS_LIMIT = 16 # longerons in one ribs +SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry +SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel +SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels def kit_work(work): @@ -1283,6 +1292,75 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): return report +class BROKKR_KITBASH_OT_shell(PolishOperator): + """Make a faceted, hollow armor shell from a loft of rings: a quad cage with crease runs and a creased rim, under + a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters, + ribs and Booleans""" + bl_idname = "brokkr_kitbash.shell" + bl_label = "Make A Shell" + object_name: bpy.props.StringProperty(name="Object", description="The shell's name: a new object, or a shell to rebuild") + sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object {rings, closed, mirror, creases, rim, flip}: rings of [x, y, z] points in the shell's own frame") + thickness: bpy.props.FloatProperty(name="Thickness", default=0.05, min=0.0009, max=1.0, description="The wall's thickness") + offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward") + levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels") + bevel: bpy.props.FloatProperty(name="Bevel", default=0.0, min=0.0, max=0.1, description="Width of the Kit Bevel on the plate's edges; 0: none") + + # the action table states thickness from 0.001: a float property rounds 0.001 up, so its bound stands just under + @kit_work + def work(self, context): + if not 1 <= len(self.object_name) <= 63: + raise Refused(f"object_name {self.object_name!r} must be 1 to 63 characters; nothing changed.") + obj = bpy.data.objects.get(self.object_name) + if obj is not None: + if obj.type != "MESH" or SHELL not in obj: + raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.") + rigid(obj) + own_mesh(obj, "rebuilding") + try: + document = json.loads(self.sheet) + except ValueError as error: + raise Refused(f"sheet is not JSON ({error}); nothing changed.") from None + built = core.sheet(document) + cage_faces = len(built.counts) + if cage_faces * 4 ** self.levels > SHELL_FACES_LIMIT: + raise Refused(f"sheet: {cage_faces} cage quads at {self.levels} levels subdivide to {cage_faces * 4 ** self.levels} faces, over {SHELL_FACES_LIMIT}. " + "Use fewer levels or a sparser sheet; nothing changed.") + rebuilt = obj is not None + if rebuilt: + mesh = obj.data + mesh.clear_geometry() + else: + mesh = bpy.data.meshes.new(self.object_name) + write_mesh(mesh, built) + ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) + mesh.edges.foreach_get("vertices", ends) + ends = np.sort(ends.reshape(-1, 2), axis=1).astype(np.int64) + order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # core.sheet lists its creases low vertex first, sorted: the edges in that order + at = np.searchsorted((ends[:, 0] * len(built.V) + ends[:, 1])[order], built.creases[:, 0] * len(built.V) + built.creases[:, 1]) + edge_weights, point_weights = np.zeros(len(mesh.edges), dtype=np.float32), np.zeros(len(built.V), dtype=np.float32) + edge_weights[order[at]] = built.weights + point_weights[built.corners] = built.corner_weights + for name, domain, weights in (("crease_edge", "EDGE", edge_weights), ("crease_vert", "POINT", point_weights)): + (mesh.attributes.get(name) or mesh.attributes.new(name, "FLOAT", domain)).data.foreach_set("value", weights) + if not rebuilt: + obj = bpy.data.objects.new(self.object_name, mesh) + context.scene.collection.objects.link(obj) + smooth = obj.modifiers.get(SUBSURF) or obj.modifiers.new(SUBSURF, "SUBSURF") + smooth.levels = smooth.render_levels = self.levels + smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", "PRESERVE_CORNERS", True + wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY") + wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True + sync_bevel(obj, self.bevel) + obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel}) + corners = built.V[built.faces.reshape(-1, 4)] + facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed + cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() + return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), + "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, + "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], + "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -1314,7 +1392,8 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, - BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs) + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs, + BROKKR_KITBASH_OT_shell) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index f663d11..2b5face 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -716,6 +716,63 @@ "doc": "the section's wall" } ] + }, + { + "name": "brokkr_kitbash.shell", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, corners, subdividedFaces, facing, thickness, offset, levels and children.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the shell's name: no object's name, or a shell's, which is then rebuilt" + }, + { + "name": "sheet", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 32000, + "doc": "the shell description, a JSON object: rings, closed, mirror, creases, rim, flip" + }, + { + "name": "thickness", + "type": "number", + "minimum": 0.001, + "maximum": 1, + "default": 0.05, + "doc": "the wall's thickness" + }, + { + "name": "offset", + "type": "number", + "minimum": -1, + "maximum": 1, + "default": -1, + "doc": "-1: the wall grows inward from the designed surface; 1: outward" + }, + { + "name": "levels", + "type": "integer", + "minimum": 1, + "maximum": 4, + "default": 3, + "doc": "subdivision levels; cage quads times 4 to the levels may not pass 262144" + }, + { + "name": "bevel", + "type": "number", + "minimum": 0, + "maximum": 0.1, + "default": 0, + "doc": "width of the Kit Bevel on the plate's edges; 0: none" + } + ] } ] } diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py new file mode 100644 index 0000000..e178482 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -0,0 +1,383 @@ +"""Live proof, in a background Blender, of brokkr_kitbash.shell through run_intent: a loft of rings becomes a cage whose +crease runs stay crisp under subdivision while the rest stays smooth, a wall of even thickness with a filled rim, a +mirror, a rebuild in place under cutters and ribs, cut_many and ribs on the shell, and the refusals. Not part of the +unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_faceted.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and exits 1 when a check failed. + +Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading +and the least claimed mutant's, both written beside it; the result file carries the readings. Costs are wall times +of this run, reported and never bounded. The checks run inside one try: an uncaught error is a failed check that +names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import statistics +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py") +core = importlib.util.module_from_spec(spec) # core as the unit tests load it +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-faceted-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "costs": {}} +COUNT, SECTION = [0], ["setup"] +WALL = 0.06 +# Degrees: the largest dihedral angle anywhere inside the subdivided pauldron (not on its rim), which is on its creased +# column. Shipped 52; least claimed mutant 6.5 (S1, crease_edge not written: the cage subdivides smooth); the geometric +# mean, separation 2.8 each side. +CRISP = 18.0 +# Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed +# mutant 51 (C1, a Subdivision that only splits, SIMPLE: every cage edge stays an edge); the geometric mean, separation +# 3 each side. S1 reads 6.5 here, 1.13 of shipped: CRISP claims it. +SOFT = 17.0 +# Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved +# the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant +# 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side. +CORNER = 1.6e-4 +# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.027 (a wall +# grown inward loses volume inside the crown's curve); least claimed mutant 0.036 (S6, the Solidify above the +# Subdivision: the wall's own edges are rounded off); the geometric mean, a total separation of 1.34. +SOLID = 0.0313 +# Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped +# 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. +EVEN = 1.5e-3 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def reading(name, value, least=False): + """The worst of a metric: the largest, or with `least` the smallest.""" + R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value)) + return float(value) + + +def section(name): + SECTION[0] = name + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "action": action, **fields}) + result = None + if receipt.get("hostResult"): + try: + result = json.loads(receipt["hostResult"]) + except ValueError: + result = None + print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, + [(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + np.round(points(o), 6).tolist() if o.type == "MESH" else None) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections) + + +def refused(label, fields, expected): + state = scene_state() + receipt, _ = send("brokkr_kitbash.shell", **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) + + +def points(obj): + V = np.zeros(3 * len(obj.data.vertices)) + obj.data.vertices.foreach_get("co", V) + return V.reshape(-1, 3) + + +def evaluated(obj, off=()): + """This script's own copy of an object evaluated with the modifiers of the named types off, as a bmesh in its frame.""" + hidden = [m for m in obj.modifiers if m.type in off and m.show_viewport] + for m in hidden: + m.show_viewport = False + try: + bpy.context.view_layer.update() + owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + bm = bmesh.new() + bm.from_mesh(owner.to_mesh()) + owner.to_mesh_clear() + finally: + for m in hidden: + m.show_viewport = True + bpy.context.view_layer.update() + bm.normal_update() + return bm + + +def dihedrals(bm): + """(degrees, crease weight, convex) of every edge between two faces.""" + layer = bm.edges.layers.float.get("crease_edge") + rows = [] + for e in bm.edges: + if len(e.link_faces) == 2: + a, b = e.link_faces + rows.append((math.degrees(a.normal.angle(b.normal, 0.0)), e[layer] if layer else 0.0, (b.calc_center_median() - a.calc_center_median()).dot(a.normal) < 0)) + return rows + + +def crease_weights(obj) -> dict: + """{(low vertex, high vertex): weight} of the cage's crease_edge attribute, weights over 0 only.""" + attribute = obj.data.attributes.get("crease_edge") + if attribute is None: + return {} + return {tuple(sorted(e.vertices)): round(attribute.data[e.index].value, 6) for e in obj.data.edges if attribute.data[e.index].value > 0} + + +def stack(obj): + return [m.name for m in obj.modifiers] + + +def ring(y, s, dip=0.0): + """One ring of the pauldron: over the crown from inboard (+x) to outboard and down the outer face, at y.""" + return [[x * s, y, z * s] for x, z in ((0.55, 1.2), (-0.2, 1.5), (-0.9, 1.35 - dip), (-1.35, 1.0), (-1.55, 0.3), (-1.65, -0.35))] + + +# A pauldron-like sheet, the one the cut's probes measured: 6 rings of 6 points running aft to fore, a concave dip in ring +# 2, the shoulder line (column 3) creased. Its rings run toward +y and its points toward -x, so by the winding rule the +# crown would face down: flip turns it up. +RINGS = [ring(-1.35, 0.85), ring(-0.8, 0.97), ring(-0.2, 1.0, dip=0.25), ring(0.4, 1.0), ring(0.9, 0.95), ring(1.2, 0.8)] +PAULDRON = {"rings": RINGS, "flip": True, "creases": [{"column": 3, "from": 0, "to": 5, "weight": 1.0}]} +CUTS = [{"name": f"Line{k}", "part": "slab", "params": "gap=0.02; length=0.8; depth=0.025", "origin": [x, y, 3.0], "direction": [0, 0, -1], **({"roll": 90} if k % 2 else {})} + for k, (x, y) in enumerate(((-0.3, -0.5), (-0.3, 0.1), (-0.6, 0.6), (0.1, 0.7)))] + [ + {"name": f"Inset{k}", "part": "box", "params": "width=0.25; height=0.2; depth=0.03", "origin": [-3.0, y, 0.5], "direction": [1, 0, 0]} for k, y in enumerate((-0.5, 0.5))] +PLANES = json.dumps([{"origin": [0.0, y, 0.0], "normal": [0.0, 1.0, 0.0]} for y in (-0.6, 0.0, 0.6)]) + +try: + # --- shell-crisp ------------------------------------------------------------------------------------------------------------ + section("shell-crisp") + request = {"object_name": "Pauldron", "sheet": json.dumps(PAULDRON), "thickness": WALL, "bevel": 0.004} + receipt, report = send("brokkr_kitbash.shell", **request) + pauldron = bpy.data.objects.get("Pauldron") + stored = json.loads(pauldron["kit_shell"]) if pauldron is not None and "kit_shell" in pauldron else {} + built = core.sheet(PAULDRON) + check("shell makes one mesh object in the scene: the cage as core.sheet builds it, vertex for vertex, and kit_shell the request", + receipt["status"] == "accepted" and pauldron is not None and pauldron.users_collection == (bpy.context.scene.collection,) and pauldron.parent is None + and np.abs(points(pauldron) - built.V).max() < 1e-6 and [tuple(p.vertices) for p in pauldron.data.polygons] == [tuple(q) for q in built.faces.reshape(-1, 4).tolist()] + and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON + and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) + check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", + report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], + report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) + and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) + smooth, wall = pauldron.modifiers.get("Kit Subsurf"), pauldron.modifiers.get("Kit Solidify") + check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled", + stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS") + and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7, + stack(pauldron)) + expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} + check("crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", crease_weights(pauldron) == expected and len(expected) == 25 + and pauldron.data.attributes.get("crease_vert") is not None and max(d.value for d in pauldron.data.attributes["crease_vert"].data) == 0.0, crease_weights(pauldron)) + designed = evaluated(pauldron, ("SOLIDIFY", "BEVEL", "BOOLEAN")) + rows = dihedrals(designed) + reading("crisp", max(angle for angle, _, _ in rows), least=True) + reading("soft", max([angle for angle, weight, _ in rows if weight == 0.0] or [180.0])) + concave = sum(1 for angle, _, convex in rows if not convex and angle > 1.0) + check("shell-crisp: the creased column stays a facet edge under three levels of subdivision, every other edge inside the plate stays smooth, and the dip is concave", + R["readings"]["crisp"] > CRISP and R["readings"]["soft"] < SOFT and len(designed.faces) == report["subdividedFaces"] and concave > 20, + [R["readings"], len(designed.faces), concave]) + + # a semi-sharp ring, a vertex crease and a soft rim, written edge for edge + MIXED = {"rings": RINGS, "flip": True, "rim": 0.0, "creases": [{"ring": 2, "from": 1, "to": 4, "weight": 0.6}, {"column": 3, "from": 0, "to": 5, "weight": 1.0}, + {"point": [4, 1], "weight": 0.8}]} + receipt, report = send("brokkr_kitbash.shell", object_name="Mixed", sheet=json.dumps(MIXED), thickness=WALL, levels=2) + mixed, built = bpy.data.objects.get("Mixed"), core.sheet(MIXED) + expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} + corner = [round(d.value, 6) for d in mixed.data.attributes["crease_vert"].data] if mixed is not None else [] + check("a semi-sharp ring run, a column run and a point land on their own edges and vertex; with rim 0 the boundary carries no crease", + receipt["status"] == "accepted" and crease_weights(mixed) == expected and sorted(set(expected.values())) == [0.6, 1.0] and len(expected) == 8 + and corner == [0.8 if k == 4 * 6 + 1 else 0.0 for k in range(36)] and (report["creases"], report["corners"], report["subdividedFaces"]) == (8, 1, 400) and "Kit Bevel" not in stack(mixed), + [receipt["message"], crease_weights(mixed)]) + surface = evaluated(mixed, ("SOLIDIFY",)) + for corner_at in (RINGS[0][0], RINGS[0][-1], RINGS[-1][0], RINGS[-1][-1]): + reading("corner", max(1e-7, min((v.co - Vector(corner_at)).length for v in surface.verts))) + surface.free() + check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"]) + + # --- shell-solid ------------------------------------------------------------------------------------------------------------ + section("shell-solid") + pauldron.modifiers["Kit Bevel"].show_viewport = False # the wall alone: a bevel rounds its edges + whole = evaluated(pauldron) + pauldron.modifiers["Kit Bevel"].show_viewport = True + area = sum(f.calc_area() for f in designed.faces) + outer = BVHTree.FromBMesh(designed) + inner = [v.co for v in whole.verts if all(outer.find_nearest(f.calc_center_median())[3] > WALL / 2 for f in v.link_faces)] + reading("solid", abs(whole.calc_volume(signed=True) / (area * WALL) - 1.0)) + for co in inner: + reading("even", abs(outer.find_nearest(co)[3] - WALL)) + check("shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", + sum(1 for e in whole.edges if not e.is_manifold) == 0 and whole.calc_volume(signed=True) > 0 and len(whole.faces) == 2 * 1600 + 4 * 40 and len(inner) > 0.9 * len(designed.verts) + and R["readings"]["solid"] < SOLID and R["readings"]["even"] < EVEN, [R["readings"], len(whole.faces), len(inner), len(designed.verts)]) + whole.free() + + # a mirrored breast sheet: symmetric as evaluated + half = [[[0.0, -0.5 - 0.05 * i, 0.3 * i], [0.3, -0.45 - 0.05 * i, 0.3 * i], [0.6, -0.2, 0.3 * i + 0.05], [0.7, 0.2, 0.3 * i]] for i in range(4)] + BREAST = {"rings": half, "mirror": True, "creases": [{"column": 1, "from": 0, "to": 3, "weight": 1.0}, {"ring": 2, "from": 0, "to": 1, "weight": 0.7}]} + receipt, report = send("brokkr_kitbash.shell", object_name="Breast", sheet=json.dumps(BREAST), thickness=0.05, levels=2) + breast = bpy.data.objects.get("Breast") + plate = evaluated(breast) if breast is not None else None + V = np.array([v.co[:] for v in plate.verts]) if plate is not None else np.zeros((1, 3)) + mirrored = {tuple(np.round(v * (-1.0, 1.0, 1.0), 5) + 0.0) for v in V} == {tuple(np.round(v, 5) + 0.0) for v in V} + check("a mirrored sheet is a plate symmetric in x, facing forward (-y), its creases on both halves", receipt["status"] == "accepted" and mirrored and report["points"] == 7 + and report["facing"][1] < -0.5 and abs(report["facing"][0]) < 1e-6 and report["creases"] == 2 * 6 + 2 * 3 + 2 * 3 + 2 + and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], report]) + if plate is not None: + plate.free() + + # --- shell-composes --------------------------------------------------------------------------------------------------------- + section("shell-composes") + receipt, cut = send("brokkr_kitbash.cut_many", object_name="Pauldron", cuts=json.dumps(CUTS)) + check("shell-composes: cut_many takes four panel lines and two insets on a shell, and its Boolean goes after the wall and above the bevel", + receipt["status"] == "accepted" and stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Difference", "Kit Bevel"] + and sorted(c.name for c in pauldron.children) == sorted(c["name"] for c in CUTS), [receipt["message"], stack(pauldron)]) + receipt, ribbed = send("brokkr_kitbash.ribs", object_name="Pauldron", ribs_name="PauldronRibs", planes=PLANES, standoff=0.01, depth=0.03, thickness=0.014) + ribs = bpy.data.objects.get("PauldronRibs") + behind = ribs is not None + for v in (points(ribs) if ribs is not None else ()): + on, normal, _, _ = outer.find_nearest(Vector(v)) + behind = behind and (Vector(v) - on).dot(normal) < 0 + check("shell-composes: ribs takes a shell, reads its thickness from Kit Solidify, and stands behind the plate: on the side the cage's normals face away from", + receipt["status"] == "accepted" and behind and ribs.parent == pauldron and ribbed["thickness"] == 0.06 and ribbed["ribs"] >= 3 and ribbed["nonManifoldEdges"] == 0, + [receipt["message"], ribbed]) + receipt, deep = send("brokkr_kitbash.ribs", object_name="Pauldron", ribs_name="PauldronDeep", planes=PLANES, standoff=0.03, depth=0.08, thickness=0.014) + R["readings"]["ribsAcrossTheCrease"] = 1.0 if receipt["status"] == "accepted" else 0.0 # a reading, not a check: deep ribs behind a creased plate are ribs' to clip or refuse + R["creaseRibs"] = str(receipt["message"])[:300] + if bpy.data.objects.get("PauldronDeep") is not None: + bpy.data.objects.remove(bpy.data.objects["PauldronDeep"]) + bpy.context.view_layer.update() + + # --- shell-rebuild ---------------------------------------------------------------------------------------------------------- + section("shell-rebuild") + before = {"pointer": pauldron.as_pointer(), "mesh": pauldron.data.as_pointer(), "children": {c.name: (c.as_pointer(), np.array(c.matrix_basis).tolist(), c.parent.name) for c in pauldron.children}, + "cutters": sorted(o.name for o in pauldron.modifiers["Kit Difference"].collection.objects), "collection": pauldron.modifiers["Kit Difference"].collection.as_pointer(), + "ribs": points(ribs).copy(), "slots": len(pauldron.material_slots)} + MOVED = {**PAULDRON, "rings": [[[x, y, z + 0.1 * (1.0 - abs(y))] for x, y, z in r] for r in RINGS]} # the crown lifted, most in the middle + receipt, report = send("brokkr_kitbash.shell", object_name="Pauldron", sheet=json.dumps(MOVED), thickness=0.05, levels=2, bevel=0.004) + again = bpy.data.objects.get("Pauldron") + wall = again.modifiers.get("Kit Solidify") + check("shell-rebuild: the same object and mesh datablock, its cutters and ribs still its children at unchanged matrices, the Boolean's collection untouched, the stack in order", + receipt["status"] == "accepted" and again is not None and (again.as_pointer(), again.data.as_pointer()) == (before["pointer"], before["mesh"]) + and {c.name: (c.as_pointer(), np.array(c.matrix_basis).tolist(), c.parent.name) for c in again.children} == before["children"] and len(before["children"]) == 7 + and (sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), again.modifiers["Kit Difference"].collection.as_pointer()) == (before["cutters"], before["collection"]) + and len(before["cutters"]) == 6 and stack(again) == ["Kit Subsurf", "Kit Solidify", "Kit Difference", "Kit Bevel"] and np.array_equal(points(ribs), before["ribs"]), + [receipt["message"], stack(again), sorted(c.name for c in again.children)]) + check("shell-rebuild: the cage is the new sheet's, the modifiers' settings and kit_shell follow, and the report says rebuilt and names the children", + report and report["rebuilt"] is True and report["children"] == sorted(before["children"]) and (report["levels"], report["thickness"], report["subdividedFaces"]) == (2, 0.05, 400) + and np.abs(points(again) - core.sheet(MOVED).V).max() < 1e-6 and abs(points(again)[:, 2].max() - (1.5 + 0.1 * 0.8)) < 1e-6 and (again.modifiers["Kit Subsurf"].levels, again.modifiers["Kit Subsurf"].render_levels) == (2, 2) + and abs(wall.thickness - 0.05) < 1e-7 and json.loads(again["kit_shell"])["sheet"] == MOVED and json.loads(again["kit_shell"])["levels"] == 2 + and crease_weights(again) == {tuple(pair): round(weight, 6) for pair, weight in zip(core.sheet(MOVED).creases.tolist(), core.sheet(MOVED).weights.tolist())}, report) + plate = evaluated(again) + check("shell-rebuild: the rebuilt plate is still cut, and closed", sum(1 for e in plate.edges if not e.is_manifold) == 0 and len(plate.faces) > 2 * 400 + 4 * 20 + 20, len(plate.faces)) + plate.free() + + # --- costs: wall times of this run, never bounded ----------------------------------------------------------------------------- + section("costs") + times = {"shell": [], "evaluation": [], "rebuildUnderCuts": []} + for k in range(3): + name = f"Timed{k}" + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(PAULDRON), thickness=WALL) + times["shell"].append(time.perf_counter() - start) + bpy.data.objects[name].update_tag() # Blender's own update after the action evaluated it already: once more, alone + start = time.perf_counter() + faces = len(bpy.data.objects[name].evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # one whole evaluation: Subdivision and Solidify + times["evaluation"].append(time.perf_counter() - start) + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004) + cut_faces = len(pauldron.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # with its one Boolean of six cutters + times["rebuildUnderCuts"].append(time.perf_counter() - start) + R["costs"] = {name: float(f"{statistics.median(values):.2g}") for name, values in times.items()} + check("costs: the timed shells evaluated whole", faces == 3360 and cut_faces > 3360, [faces, cut_faces]) + + # --- shell-refusals --------------------------------------------------------------------------------------------------------- + section("shell-refusals") + SHEET = json.dumps(PAULDRON) + plain = bpy.data.objects.new("Plain", bpy.data.meshes.new("Plain")) + plain.data.from_pydata([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [], [(0, 1, 2, 3)]) + bpy.context.scene.collection.objects.link(plain) + empty = bpy.data.objects.new("Empty", None) + bpy.context.scene.collection.objects.link(empty) + bpy.context.view_layer.update() + refused("a mesh of that name that is no shell", {"object_name": "Plain", "sheet": SHEET}, "An object named 'Plain' exists and is no shell") + refused("an object of that name that is no mesh", {"object_name": "Empty", "sheet": SHEET}, "An object named 'Empty' exists and is no shell") + refused("a ribs object", {"object_name": "PauldronRibs", "sheet": SHEET}, "An object named 'PauldronRibs' exists and is no shell") + mixed.scale = (1.0, 1.0, 1.01) + bpy.context.view_layer.update() + refused("a scaled shell", {"object_name": "Mixed", "sheet": SHEET}, "'Mixed' is scaled, mirrored or sheared in the world") + mixed.scale = (1.0, 1.0, 1.0) + twin = bpy.data.objects.new("Twin", mixed.data) + bpy.context.scene.collection.objects.link(twin) + bpy.context.view_layer.update() + refused("a shell that shares its mesh", {"object_name": "Mixed", "sheet": SHEET}, "'Mixed' shares its mesh 'Mixed' with 1 other user(s)") + bpy.data.objects.remove(twin) + bpy.context.view_layer.update() + uneven = {"rings": [RINGS[0], RINGS[1][:5]]} + refused("a sheet of unequal rings, on a new name", {"object_name": "New", "sheet": json.dumps(uneven)}, "sheet.rings[1] has 5 points and sheet.rings[0] has 6") + refused("a sheet of unequal rings, on a shell", {"object_name": "Mixed", "sheet": json.dumps(uneven)}, "sheet.rings[1] has 5 points and sheet.rings[0] has 6") + refused("a run past the ring", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 0, "from": 0, "to": 6, "weight": 1}]})}, + "sheet.creases[0].to must be a whole number from 0 to 5, not 6") + refused("two weights on one edge", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 1}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]})}, + "sheet.creases[1] gives an edge weight 0.5 that sheet.creases[0] gives 1") + refused("a sheet that is not JSON", {"object_name": "Mixed", "sheet": "{rings"}, "sheet is not JSON") + refused("a sheet with an unknown key", {"object_name": "New", "sheet": json.dumps({**PAULDRON, "inside": [0, 0, 0]})}, "sheet has no key 'inside'") + dense = {"rings": [[[j / 10, 0, i / 10] for j in range(34)] for i in range(34)]} + refused("too many faces", {"object_name": "New", "sheet": json.dumps(dense), "levels": 4}, "1089 cage quads at 4 levels subdivide to 278784 faces, over 262144") + receipt, report = send("brokkr_kitbash.shell", object_name="Dense", sheet=json.dumps(dense), levels=3, thickness=0.01) + check("the same sheet at three levels is taken", receipt["status"] == "accepted" and report["subdividedFaces"] == 69696, receipt["message"]) + check("no refusal made an object", "New" not in bpy.data.objects, None) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") + for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", R["readings"], R["costs"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json new file mode 100644 index 0000000..783d9fc --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -0,0 +1,166 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "shell makes one mesh object in the scene: the cage as core.sheet builds it, vertex for vertex, and kit_shell the request", + "ok": true, + "detail": null + }, + { + "name": "shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", + "ok": true, + "detail": null + }, + { + "name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled", + "ok": true, + "detail": null + }, + { + "name": "crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", + "ok": true, + "detail": null + }, + { + "name": "shell-crisp: the creased column stays a facet edge under three levels of subdivision, every other edge inside the plate stays smooth, and the dip is concave", + "ok": true, + "detail": null + }, + { + "name": "a semi-sharp ring run, a column run and a point land on their own edges and vertex; with rim 0 the boundary carries no crease", + "ok": true, + "detail": null + }, + { + "name": "shell-crisp: a sheet whose rim is soft keeps its four corners", + "ok": true, + "detail": null + }, + { + "name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", + "ok": true, + "detail": null + }, + { + "name": "a mirrored sheet is a plate symmetric in x, facing forward (-y), its creases on both halves", + "ok": true, + "detail": null + }, + { + "name": "shell-composes: cut_many takes four panel lines and two insets on a shell, and its Boolean goes after the wall and above the bevel", + "ok": true, + "detail": null + }, + { + "name": "shell-composes: ribs takes a shell, reads its thickness from Kit Solidify, and stands behind the plate: on the side the cage's normals face away from", + "ok": true, + "detail": null + }, + { + "name": "shell-rebuild: the same object and mesh datablock, its cutters and ribs still its children at unchanged matrices, the Boolean's collection untouched, the stack in order", + "ok": true, + "detail": null + }, + { + "name": "shell-rebuild: the cage is the new sheet's, the modifiers' settings and kit_shell follow, and the report says rebuilt and names the children", + "ok": true, + "detail": null + }, + { + "name": "shell-rebuild: the rebuilt plate is still cut, and closed", + "ok": true, + "detail": null + }, + { + "name": "costs: the timed shells evaluated whole", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a mesh of that name that is no shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an object of that name that is no mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ribs object", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a scaled shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a shell that shares its mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet of unequal rings, on a new name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet of unequal rings, on a shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a run past the ring", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: two weights on one edge", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet with an unknown key", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: too many faces", + "ok": true, + "detail": null + }, + { + "name": "the same sheet at three levels is taken", + "ok": true, + "detail": null + }, + { + "name": "no refusal made an object", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "corner": 1.8e-07, + "crisp": 52.0, + "even": 0.0001, + "ribsAcrossTheCrease": 1.0, + "soft": 5.8, + "solid": 0.027 + }, + "costs": { + "shell": 0.0035, + "evaluation": 0.0017, + "rebuildUnderCuts": 0.92 + }, + "creaseRibs": "Operator brokkr_kitbash.ribs finished.", + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 1606308..ab0d8c5 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1561,7 +1561,8 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", - "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"] + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs", + "brokkr_kitbash.shell"] class HostFileTests(unittest.TestCase): @@ -1627,7 +1628,18 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) for row in self.document["actions"][4:]: - self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) + self.assertTrue(all(field["type"] in ("string", "number", "integer") for field in row["fields"]), row["name"]) + self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"], + [("brokkr_kitbash.shell", "levels")]) + sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]}) + shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet} + self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel")], [0.05, -1, 3, 0]) + self.assertEqual(at.validate({**shell, "thickness": 0.001, "levels": 4}, host)["levels"], 4) + for bad in ({**shell, "levels": 5}, {**shell, "levels": 2.5}, {**shell, "levels": 0}, {**shell, "thickness": 0.0005}, {**shell, "offset": 1.5}, {**shell, "bevel": 0.2}, + {**shell, "sheet": "{" + " " * 32000}, {**shell, "sheet": ""}, {k: v for k, v in shell.items() if k != "sheet"}, {**shell, "object_name": "x" * 64}, + {**shell, "rings": []}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]): + at.validate(bad, host) def test_the_ribs_row_takes_64_planes_and_16_longerons_at_full_precision(self): """planes-string-cap-below-64. A float's longest repr is 24 characters (-1.2345678901234567e-05): 64 planes of @@ -1719,6 +1731,13 @@ class OwnershipTests(unittest.TestCase): for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) + shell = bodies["shell"] # shell evaluates nothing: Blender's own update after the action evaluates the plate once + for call in ("evaluated_of(", "evaluable(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"): + self.assertNotIn(call, shell) + self.assertLess(shell.rindex("raise Refused("), shell.index("clear_geometry()")) # every refusal before any write + self.assertLess(shell.index("core.sheet("), shell.index("clear_geometry()")) + self.assertLess(shell.index("clear_geometry()"), shell.index("bpy.data.meshes.new(")) + self.assertNotIn("objects.remove(", shell) # a rebuild rewrites the mesh in place: a new object would orphan its cutters and ribs self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs def test_only_ribs_writes_kit_ribs(self): @@ -1730,6 +1749,20 @@ class OwnershipTests(unittest.TestCase): self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0]) self.assertEqual(len(re.findall(r'\[RIBS\]|\bRIBS\b(?! =)|"kit_ribs"', source)), 2) # the constant's own line, and that write + def test_only_shell_writes_kit_shell(self): + """kit_shell is the request a shell's cage is derived from: shell assigns it once, and elsewhere it is only + asked for (its presence admits a rebuild); shell alone names its two modifiers and its crease attributes.""" + source = self.sources()["__init__.py"] + body = source.split("class BROKKR_KITBASH_OT_shell(")[1].split("class BROKKR_KITBASH_OT_")[0] + writes = re.findall(r'[^\n]*\[(?:SHELL|"kit_shell")\]\s*=(?!=)[^\n]*', source) + self.assertEqual(len(writes), 1) + self.assertIn(writes[0], body) + self.assertEqual(len(re.findall(r'\bSHELL\b|"kit_shell"', source.replace(body, ""))), 2) # outside shell: the constant's own line, its name and its value + self.assertEqual(re.findall(r"\[SHELL\]|SHELL not in obj|SHELL in obj", body), ["SHELL not in obj", "[SHELL]"]) + for name in ("SUBSURF", "SOLIDIFY", '"crease_edge"', '"crease_vert"'): + self.assertEqual(len(re.findall(rf"(? Date: Wed, 2 Dec 2026 11:37:49 +0100 Subject: [PATCH 03/10] docs/kitbash.md: Making a shell The sheet format with a worked pauldron, the winding rule, crease runs and rim, what a rebuild keeps, outlines by through cuts, ribs on a shell, the refusals and the measured costs. The operator count is sixteen. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 78 ++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 92c1b8e..7459c67 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1,12 +1,12 @@ # Kitbash parts: machinery from kits `surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates -them **socket** to socket, cuts them with booleans and bakes them. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +them **socket** to socket, cuts them with booleans and bakes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the fourteen operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the sixteen operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -306,9 +306,80 @@ so what is attached to it stays attached and new parts can attach to it, and it `set_params` refuses it, since the params no longer make the mesh. `exportGltf` with `applyModifiers` already exports the evaluated mesh; `apply` is for a baked `.blend`. +## Making a shell + +`shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that +are facets' borders, give it a wall, then cut into it. The cage is a **loft**: rings of points with equal counts, +quads between neighbouring rings. The description is a JSON object, `sheet`: + +| key | default | what it says | +| --- | --- | --- | +| `rings` | required | 2 to 64 rings of 2 to 64 `[x, y, z]` points in the shell's own frame, equal counts | +| `closed` | `false` | each ring joins back to its first point (a sleeve); not with `mirror` | +| `mirror` | `false` | each ring is authored from its point 0 on x = 0 toward +x and mirrored across x: 2C - 1 points | +| `creases` | `[]` | runs: `{"ring": i, "from": a, "to": b, "weight": w}`, `{"column": j, "from": a, "to": b, "weight": w}`, `{"point": [i, j], "weight": w}` | +| `rim` | `1` | the weight of every boundary edge no run names | +| `flip` | `false` | reverse every face | + +**Winding.** Quad (i, j) is `P[i][j], P[i][j+1], P[i+1][j+1], P[i+1][j]`: the surface faces out where, seen from +outside, a ring's points run left to right and the rings run upward. If the report's `facing` (the cage's mean +normal) points into the machine, set `flip` or author the rings the other way. Outward matters: the wall grows +inward from the designed surface (`offset` -1), `cut` rays must meet the outer face, and `ribs` stands on the +side the normals face away from. + +**Creases.** A ring run creases ring `i`'s edges from point `from` to point `to`; a column run creases column +`j`'s edges from ring `from` to ring `to`; a point is one vertex. A weight of 1 is a hard facet edge, and lower +weights are semi-sharp: on the pauldron below, 1.0 holds 52 degrees across the shoulder line and 0.6 holds 35, +while every edge that carries no crease stays under 6. Runs are partial on purpose: a facet edge that dies out +halfway along a plate is a run that stops there. An edge has one weight; two runs that give it different ones are +refused, naming both. On a mirrored sheet a run names authored indices and lands on both halves, and a ring run +from point 0 joins across the middle. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the +outline rounds between the corners, which stay (the Subdivision preserves them). + +```json +{"action": "brokkr_kitbash.shell", "object_name": "Pauldron", "thickness": 0.06, "bevel": 0.004, + "sheet": "{\"flip\": true, \"creases\": [{\"column\": 3, \"from\": 0, \"to\": 5, \"weight\": 1.0}], \"rings\": [[[0.47, -1.35, 1.02], [-0.17, -1.35, 1.28], [-0.77, -1.35, 1.15], [-1.15, -1.35, 0.85], [-1.32, -1.35, 0.26], [-1.4, -1.35, -0.3]], ...]}"} +``` + +Six rings of six points run aft to fore; each goes over the crown from inboard and down the outer face, and +column 3, the shoulder line, is creased, so the crown and the steep outer face are two facets of one plate. Ring 2 +dips: the plate is concave there, which no convex hull can be. + +The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers `Kit Subsurf` (`levels`, creases +used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit +Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a +part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, +`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `corners`, `subdividedFaces`, `facing`, +`thickness`, `offset`, `levels` and `children`, all facts of the cage: it reads no evaluated mesh. + +**Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh +datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is +cut. Cutters stay at their frames in the shell's frame: where the surface moved away from a cutter the cut is +shallower or floats, so raise the cutter's `lift` or `depth` (`set_params`), or cut again. Ribs are a bake: after a +rebuild, delete them and run `ribs` again. A name that is some other object is refused, as are a scaled shell and +one that shares its mesh. + +**Outlines.** A loft's outline is its first and last rings and its end columns. Notches and tabs in it are +through cuts at the rim: a `box` or `slot` cutter deeper than the wall, placed across the edge, takes a bite out of +the outline, and the plate left between two bites is a tab. + +**With ribs.** `ribs` reads the plate's thickness from `Kit Solidify` and follows a crease, clipping a rib inside +it; a rib deeper than the room a tight crease leaves is refused with the size to lower. + +Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite +number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed +corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out +of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (cage quads +times 4 to the `levels`). + +On the pauldron (25 cage quads, 1600 subdivided faces, 3360 with the wall), `shell` took 3.5 ms a call with +Blender's own update after it, and one whole evaluation of the Subdivision and Solidify 1.7 ms. With six cutters +(four panel lines, two insets) and ribs under it, a rebuild took 0.92 s, which is its one Boolean evaluation. +Medians of 3, interleaved, Blender 5.3 on Starfire (`tests/live/kitbash_faceted.py`, `costs`). + ## Cutting a shell -An armor plate is not a kit part: it is any mesh, usually a subdivided cage with a Solidify. `cut` cuts it, or a +An armor plate is not a kit part: it is any mesh, usually one made by `shell`. `cut` cuts it, or a kit part, where a ray meets it, and what it places is itself a kit part, of the kit `cutters`: | part | params (besides `depth`, `lift`) | socket | @@ -498,6 +569,7 @@ vertices overflow. | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | +| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. From 39a3b7a3dd7b8f54224d02b6884d8d0e6156b901 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 11:48:55 +0100 Subject: [PATCH 04/10] docs/kitbash.md: a closed loop of crease runs needs point creases at its corners Found building Seraph's pectoral block: the face's border rounded into a disc. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7459c67..7dd057d 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -333,7 +333,9 @@ weights are semi-sharp: on the pauldron below, 1.0 holds 52 degrees across the s while every edge that carries no crease stays under 6. Runs are partial on purpose: a facet edge that dies out halfway along a plate is a run that stops there. An edge has one weight; two runs that give it different ones are refused, naming both. On a mirrored sheet a run names authored indices and lands on both halves, and a ring run -from point 0 joins across the middle. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the +from point 0 joins across the middle. A vertex where exactly two creased edges meet is smoothed along them, so a +closed loop of runs (a raised face's border) rounds into a disc unless each of its corners is also a `point`; +where three or more meet, or a run ends on the rim, the corner holds by itself. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the outline rounds between the corners, which stay (the Subdivision preserves them). ```json From dddef79d8df4695be20d697c9bff16daf3ae78a3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:10:30 +0100 Subject: [PATCH 05/10] live kitbash, kitbash_assembly: the rows the host must load are the action table's, read from brokkr_actions.json Both suites listed the kitbash rows by hand, ending at ribs, and failed once shell added a row. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash.py | 5 +++-- surfaces/blender/tests/live/kitbash.result.json | 3 ++- surfaces/blender/tests/live/kitbash_assembly.py | 5 +++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 9c48891..609051a 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -49,6 +49,8 @@ target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "hostRows": [row["name"] for row in target.host_actions()[0]]} COUNT = [0] +# the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows +TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] def check(name, ok, detail=None): @@ -74,8 +76,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], R["hostRows"]]) + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 7d2950a..8e751b7 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -420,7 +420,8 @@ "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", - "brokkr_kitbash.ribs" + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell" ], "placed": { "nozzle": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 3802282..5e73eac 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -59,6 +59,8 @@ target.configure_action_dirs("", str(WORK)) target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} COUNT = [0] +# the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows +TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] kit = core.load_kit("mechanical") # Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from # the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least @@ -176,8 +178,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], rows]) +check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [], [R["hostErrors"], rows]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 From b5b32efe94b0dde8f8dd3953a2bd739779e98ef4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:10:30 +0100 Subject: [PATCH 06/10] live kitbash_faceted: a failed check whose detail is keyed by vertex pairs is written, not a crash; W1 claimed by the edge-for-edge check json.dumps refused the tuple keys of a failed crease check's detail, so a mutant that broke the crease order ended in a traceback with no FAIL line. shell's comment says why the weights are looked up by vertex pair: the mesh's edge order is not core.sheet's. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 2 +- surfaces/blender/tests/live/kitbash_faceted.py | 7 +++++++ surfaces/blender/tests/live/kitbash_faceted.result.json | 6 +++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 95204fb..6dfab56 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1335,7 +1335,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) mesh.edges.foreach_get("vertices", ends) ends = np.sort(ends.reshape(-1, 2), axis=1).astype(np.int64) - order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # core.sheet lists its creases low vertex first, sorted: the edges in that order + order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # the mesh lists its edges in calc_edges' order, not by vertex pair: each of core.sheet's creases is found by its pair at = np.searchsorted((ends[:, 0] * len(built.V) + ends[:, 1])[order], built.creases[:, 0] * len(built.V) + built.creases[:, 1]) edge_weights, point_weights = np.zeros(len(mesh.edges), dtype=np.float32), np.zeros(len(built.V), dtype=np.float32) edge_weights[order[at]] = built.weights diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index e178482..90f018b 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -70,6 +70,8 @@ CRISP = 18.0 # Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed # mutant 51 (C1, a Subdivision that only splits, SIMPLE: every cage edge stays an edge); the geometric mean, separation # 3 each side. S1 reads 6.5 here, 1.13 of shipped: CRISP claims it. +# W1 (the weights written at the creases' own indices, not at the edges found by vertex pair) reads 25 here and is +# claimed by the exact check below, crease_edge edge for edge: it has no bound to sit under. SOFT = 17.0 # Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved # the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant @@ -85,6 +87,10 @@ EVEN = 1.5e-3 def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by vertex pairs: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) @@ -211,6 +217,7 @@ try: stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS") and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7, stack(pauldron)) + # W1 dies here: the mesh's edges are not in the order core.sheet lists its creases, so the weights must be looked up by pair expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} check("crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", crease_weights(pauldron) == expected and len(expected) == 25 and pauldron.data.attributes.get("crease_vert") is not None and max(d.value for d in pauldron.data.attributes["crease_vert"].data) == 0.0, crease_weights(pauldron)) diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 783d9fc..f1594a2 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -157,9 +157,9 @@ "solid": 0.027 }, "costs": { - "shell": 0.0035, - "evaluation": 0.0017, - "rebuildUnderCuts": 0.92 + "shell": 0.0036, + "evaluation": 0.0018, + "rebuildUnderCuts": 0.97 }, "creaseRibs": "Operator brokkr_kitbash.ribs finished.", "ok": true From 2e22a58bd794dc1e01e80cf0939da09e027da5c1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:10:31 +0100 Subject: [PATCH 07/10] docs/kitbash.md: the thickness a crease holds, as measured Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7dd057d..7b3816b 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -368,6 +368,19 @@ the outline, and the plate left between two bites is a tab. **With ribs.** `ribs` reads the plate's thickness from `Kit Solidify` and follows a crease, clipping a rib inside it; a rib deeper than the room a tight crease leaves is refused with the size to lower. +**Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot +hold: it reads no evaluated mesh, and the limit is a fact of the subdivided one. Even thickness moves a vertex on a +full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half +the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than +the first row of subdivided faces, the wall's inner face folds over itself beside the crease: at a `thickness` over +(W / 2^`levels`) / tan(phi), W the facet's width across the crease. Measured on a ridge of two flat facets under a +wall grown inward, a crease of 1.0: the fold starts at 1.00 of that figure in 13 readings (W 1 and 0.4; phi 30, 45, +60; levels 1 to 3), which is 0.217 for W 1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. A crease of +0.5 folds at 1.02 to 1.3 of it, and an uncreased ridge folds too, at 1.1 to 4.2 of it. The fold is inside the +wall and one subdivided row wide: the designed surface is unchanged and the mesh has no open or non-manifold +edge, but the solid passes through itself there, and a cut through that place is untested. Keep `thickness` +under the figure where a creased plate is cut near its crease: a thinner wall, fewer `levels`, or wider facets. + Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out From 9556d1337c2843f5cafc6fcc704d419ccbff955c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:46:53 +0100 Subject: [PATCH 08/10] brokkr_kitbash.shell: the receipt names the thickness at which the cage says the wall folds; live suites print before they write shell reports fold {onset, margin, edge, weight} from the cage alone (core.fold_depths: every edge between two quads as a full crease between flat facets, the narrower facet's reach, the wall's share on the edge's concave side from offset). It reads no evaluated mesh. An estimate: on the Seraph's fourteen creased plates the evaluated wall first folded at 0.74 to 1.2 of it in thirteen and at 2.6 in one. kitbash_faceted checks it against the evaluated wall on a wedge of unequal facets (no turned inner face at onset / 1.2, some at onset x 1.2). docs/kitbash.md: the narrower facet binds; 23 of 23 readings, ridge and valley; the fold receipt. kitbash_faceted: SOFT sits at 12, between shipped 5.8 and W1's 25, and its comment says W1 is its least mutant. kitbash, kitbash_assembly, kitbash_pose, mesh_polish, rig: check() takes a detail the result file cannot, and the CHECK lines are printed before the file is written. kitbash, kitbash_assembly: the action table is also held against the operators the add-on registered, so a row lost from the table fails live. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 9 + .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/brokkr_kitbash/core.py | 37 ++++ surfaces/blender/docs/kitbash.md | 36 +++- surfaces/blender/tests/live/kitbash.py | 10 +- .../blender/tests/live/kitbash_assembly.py | 10 +- .../blender/tests/live/kitbash_faceted.py | 46 ++++- .../tests/live/kitbash_faceted.result.json | 18 +- surfaces/blender/tests/live/kitbash_pose.py | 6 +- surfaces/blender/tests/live/mesh_polish.py | 6 +- .../tests/live/mesh_polish.result.json | 189 ++++-------------- surfaces/blender/tests/live/rig.py | 6 +- surfaces/blender/tests/live/rig.result.json | 10 +- surfaces/blender/tests/test_kitbash.py | 28 +++ 14 files changed, 225 insertions(+), 188 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 6dfab56..c557c76 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1355,7 +1355,16 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): corners = built.V[built.faces.reshape(-1, 4)] facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() + pairs, depths, ridges, weights = core.fold_depths(built, self.levels) + behind, front = 0.5 * (1.0 - self.offset), 0.5 * (1.0 + self.offset) # the wall's share behind the designed surface, and in front of it + with np.errstate(divide="ignore"): + onsets = depths / np.where(ridges, behind, front) # the thickness at which each cage edge's concave side holds its fold depth + first = int(onsets.argmin()) if len(onsets) and np.isfinite(onsets.min()) else None + fold = None if first is None else { + "onset": round(float(onsets[first]), 6), "margin": round(float(onsets[first]) / self.thickness, 4), + "edge": [[int(v) // built.points, int(v) % built.points] for v in pairs[first]], "weight": round(float(weights[first]), 6)} return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), + "fold": fold, "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 2b5face..f286fd1 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -719,7 +719,7 @@ }, { "name": "brokkr_kitbash.shell", - "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, corners, subdividedFaces, facing, thickness, offset, levels and children.", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, fold ({onset, margin, edge, weight}: the thickness at which the cage says the wall first folds over itself beside an edge, onset over the thickness asked, the edge as two [ring, point] and its crease; null where no edge can fold; an estimate from the cage, margin under 1 is a folded wall), corners, subdividedFaces, facing, thickness, offset, levels and children.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index d6156c9..f932bd5 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1134,6 +1134,43 @@ def sheet(document: Any) -> Sheet: corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) +def fold_depths(built: Sheet, levels: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Where an even wall on a shell's cage would fold, from the cage alone: for every cage edge between two quads, + (pairs (E, 2) of vertex indices, depth (E,), ridge (E,), weight (E,)). depth is the wall depth on the edge's + concave side at which the wall's far face first folds over itself beside the edge when the edge is a full + crease between flat facets: (W / 2^levels) / tan(phi), W the lesser perpendicular reach of the two quads from + the edge (the narrower facet binds) and phi half the angle between their normals; infinite where they are + coplanar. ridge: the facets fall away from their normals, so the concave side is behind the surface (a wall + grown inward); else it is in front. weight is the edge's crease, 0 where it has none: under a full crease a + softer edge folds later than its depth, never sooner.""" + quads = built.faces.reshape(-1, 4) + V = built.V + normals = np.cross(V[quads[:, 2]] - V[quads[:, 0]], V[quads[:, 3]] - V[quads[:, 1]]) + normals /= np.linalg.norm(normals, axis=1)[:, None] + centres = V[quads].mean(axis=1) + sides = {} + for face, quad in enumerate(quads): + for k in range(4): + a, b = int(quad[k]), int(quad[(k + 1) % 4]) + sides.setdefault((min(a, b), max(a, b)), []).append((face, int(quad[(k + 2) % 4]), int(quad[(k + 3) % 4]))) + creased = {(int(a), int(b)): float(w) for (a, b), w in zip(built.creases, built.weights)} + pairs, depths, ridges, weights = [], [], [], [] + for (a, b), faces in sorted(sides.items()): + if len(faces) != 2: + continue + along = V[b] - V[a] + along /= np.linalg.norm(along) + reach = min(float(np.linalg.norm((V[v] - V[a]) - along * ((V[v] - V[a]) @ along))) for _, c, d in faces for v in (c, d)) + (f0, _, _), (f1, _, _) = faces + middle = 0.5 * (V[a] + V[b]) + phi = 0.5 * math.acos(float(np.clip(normals[f0] @ normals[f1], -1.0, 1.0))) + pairs.append((a, b)) + depths.append(reach / 2 ** levels / math.tan(phi) if phi > 1e-9 else math.inf) + ridges.append(bool(normals[f0] @ (centres[f1] - middle) + normals[f1] @ (centres[f0] - middle) < 0)) + weights.append(creased.get((a, b), 0.0)) + return np.array(pairs, dtype=np.int64).reshape(-1, 2), np.array(depths), np.array(ridges, dtype=bool), np.array(weights) + + # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7b3816b..32fea95 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -351,8 +351,9 @@ The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, -`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `corners`, `subdividedFaces`, `facing`, -`thickness`, `offset`, `levels` and `children`, all facts of the cage: it reads no evaluated mesh. +`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `fold` (see Thickness at a crease), +`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`, all facts of the cage: it +reads no evaluated mesh. **Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is @@ -372,14 +373,27 @@ it; a rib deeper than the room a tight crease leaves is refused with the size to hold: it reads no evaluated mesh, and the limit is a fact of the subdivided one. Even thickness moves a vertex on a full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than -the first row of subdivided faces, the wall's inner face folds over itself beside the crease: at a `thickness` over -(W / 2^`levels`) / tan(phi), W the facet's width across the crease. Measured on a ridge of two flat facets under a -wall grown inward, a crease of 1.0: the fold starts at 1.00 of that figure in 13 readings (W 1 and 0.4; phi 30, 45, -60; levels 1 to 3), which is 0.217 for W 1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. A crease of -0.5 folds at 1.02 to 1.3 of it, and an uncreased ridge folds too, at 1.1 to 4.2 of it. The fold is inside the -wall and one subdivided row wide: the designed surface is unchanged and the mesh has no open or non-manifold -edge, but the solid passes through itself there, and a cut through that place is untested. Keep `thickness` -under the figure where a creased plate is cut near its crease: a thinner wall, fewer `levels`, or wider facets. +the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over +(W / 2^`levels`) / tan(phi), W the width across the crease of the narrower of its two facets. The fold is on the +crease's concave side: behind a ridge, so under a wall grown inward, and in front of a valley, under a wall grown +outward; the two read the same. Measured on two flat facets, a crease of 1.0: the fold starts at 1.00 of that +figure in 23 of 23 readings (W 1 and 0.4; phi 15 to 60; levels 1 to 3; a ridge and a valley), which is 0.217 for W +1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at +0.075, the narrow facet's figure, not the wide one's 0.25. A crease of 0.5 folds at 1.02 to 1.32 of it, and an +uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and one subdivided row wide: the +designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself +there, and a cut through that place is untested. + +`shell` reports this at the call, from the cage: `fold` is `{onset, margin, edge, weight}`, or null where no cage +edge has a wall on its concave side. `onset` is the least `thickness` at which the figure above says some cage edge +folds, every edge between two quads taken as a full crease between flat facets, and the wall's share on that edge's +concave side taken from `offset`; `margin` is `onset` over the `thickness` asked, so under 1 the wall is expected to +fold; `edge` is that edge as two `[ring, point]` (points as built: 2C - 1 on a mirrored ring), and `weight` its +crease. It is an estimate: a `weight` under 1 folds later than `onset`, and where a crease runs out to the rim +through a tapering quad the wall can fold sooner. On the Seraph's fourteen creased plates the evaluated wall first +folded at 0.74 to 1.2 of `onset` in thirteen and at 2.6 of it in one, whose binding edge had a crease of 0.6 +(`experiments/mechs`, 2026-12-02). Keep `margin` over about 1.4 where a plate is cut near a crease, with a thinner +wall, fewer `levels` or wider facets, and count the turned inner faces of the evaluated wall when it matters. Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed @@ -584,7 +598,7 @@ vertices overflow. | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | -| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | +| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `fold` (`{onset, margin, edge, weight}`: the thickness at which the cage says the wall first folds beside an edge, or null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 609051a..d3d94e2 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -51,9 +51,15 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT = [0] # the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] +# the operators the add-on registered: each is an action the table must have a row for, so a row lost from the table is seen +OPERATORS = sorted(f"brokkr_kitbash.{name}" for name in dir(bpy.ops.brokkr_kitbash)) def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised @@ -76,7 +82,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [], [R["hostErrors"], R["hostRows"]]) + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") @@ -255,7 +261,7 @@ check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} R["ok"] = all(c["ok"] for c in R["checks"]) -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 5e73eac..805e576 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -61,6 +61,8 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT = [0] # the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] +# the operators the add-on registered: each is an action the table must have a row for, so a row lost from the table is seen +OPERATORS = sorted(f"brokkr_kitbash.{name}" for name in dir(bpy.ops.brokkr_kitbash)) kit = core.load_kit("mechanical") # Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from # the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least @@ -86,6 +88,10 @@ NUDGE = 3.2e-4 def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised @@ -178,7 +184,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [], [R["hostErrors"], rows]) +check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], rows, OPERATORS]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 @@ -709,8 +715,8 @@ check("and each face keeps its own slot: the cutter's brass faces are brass, the R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") print("READINGS", R["readings"], flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index 90f018b..4d04ed4 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -68,11 +68,11 @@ WALL = 0.06 # mean, separation 2.8 each side. CRISP = 18.0 # Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed -# mutant 51 (C1, a Subdivision that only splits, SIMPLE: every cage edge stays an edge); the geometric mean, separation -# 3 each side. S1 reads 6.5 here, 1.13 of shipped: CRISP claims it. -# W1 (the weights written at the creases' own indices, not at the edges found by vertex pair) reads 25 here and is -# claimed by the exact check below, crease_edge edge for edge: it has no bound to sit under. -SOFT = 17.0 +# mutant 25 (W1, the weights written at the creases' own indices, not at the edges found by vertex pair: a crease +# lands on an edge that should have none); the geometric mean, separation 2.07 each side. C1 (a Subdivision that only +# splits, SIMPLE: every cage edge stays an edge) reads 51 here. S1 reads 6.5, 1.13 of shipped: CRISP claims it. W1 is +# also caught by the exact check below, crease_edge edge for edge. +SOFT = 12.0 # Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved # the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant # 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side. @@ -84,6 +84,11 @@ SOLID = 0.0313 # Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped # 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. EVEN = 1.5e-3 +# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet. The +# wall is built at FOLD / FOLD_STEP (no inner face turned) and at FOLD x FOLD_STEP (some turned). Least claimed mutant: +# F1, the wider facet's reach taken (max for min in core.fold_depths), which reads 0.25, 3.3 of shipped; FOLD_STEP is +# the 1.2 separation the margin rule asks on each side of the onset. +FOLD, FOLD_STEP = 0.075, 1.2 def check(name, ok, detail=None): @@ -208,7 +213,7 @@ try: and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", - report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "fold", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) @@ -247,6 +252,35 @@ try: surface.free() check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"]) + # --- shell-fold: the receipt's fold onset, against the evaluated wall --------------------------------------------------------- + section("shell-fold") + # a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075 + wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)], + "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]} + + def folded(name, thickness, offset=-1.0): + """(the receipt's fold, inner faces of the evaluated wall whose normal runs with their outer face's).""" + _, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(wedge), thickness=thickness, offset=offset, levels=2) + wall_mesh = evaluated(bpy.data.objects[name]) + wall_mesh.faces.ensure_lookup_table() + count = len(bpy.data.objects[name].data.polygons) * 4 ** 2 # Solidify lists the outer faces, then their inner twins in the same order, then the rim + turned = sum(1 for k in range(count) if wall_mesh.faces[k].normal.dot(wall_mesh.faces[count + k].normal) > 0) + wall_mesh.free() + return told["fold"], turned + + under, over = folded("FoldUnder", FOLD / FOLD_STEP), folded("FoldOver", FOLD * FOLD_STEP) + reading("foldUnder", under[1]) + reading("foldOver", over[1], least=True) + check("shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", + abs(under[0]["onset"] - FOLD) < 1e-6 and abs(under[0]["margin"] - FOLD_STEP) < 1e-3 and abs(over[0]["margin"] - 1 / FOLD_STEP) < 1e-3 + and under[0]["edge"] in ([[0, 1], [1, 1]], [[1, 1], [2, 1]]) and under[0]["weight"] == 1.0 and under[1] == 0 and over[1] > 0, [under, over]) + outward = folded("FoldOut", 0.3, offset=1.0) + half = folded("FoldHalf", FOLD / FOLD_STEP, offset=0.0) + check("shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", + outward == (None, 0) and abs(half[0]["onset"] - 2 * FOLD) < 1e-6 and half[1] == 0, [outward, half]) + for name in ("FoldUnder", "FoldOver", "FoldOut", "FoldHalf"): + bpy.data.objects.remove(bpy.data.objects[name]) + # --- shell-solid ------------------------------------------------------------------------------------------------------------ section("shell-solid") pauldron.modifiers["Kit Bevel"].show_viewport = False # the wall alone: a bevel rounds its edges diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index f1594a2..5523476 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -36,6 +36,16 @@ "ok": true, "detail": null }, + { + "name": "shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", + "ok": true, + "detail": null + }, + { + "name": "shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", + "ok": true, + "detail": null + }, { "name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", "ok": true, @@ -152,14 +162,16 @@ "corner": 1.8e-07, "crisp": 52.0, "even": 0.0001, + "foldOver": 8.0, + "foldUnder": 0.0, "ribsAcrossTheCrease": 1.0, "soft": 5.8, "solid": 0.027 }, "costs": { - "shell": 0.0036, - "evaluation": 0.0018, - "rebuildUnderCuts": 0.97 + "shell": 0.0074, + "evaluation": 0.0015, + "rebuildUnderCuts": 1.1 }, "creaseRibs": "Operator brokkr_kitbash.ribs finished.", "ok": true diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 95d0b3d..de26a6f 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -84,6 +84,10 @@ EDGE, PAST = 1e-5, 3.2e-5 def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised @@ -304,8 +308,8 @@ refused("an axis that is not one of the six, by the action table", "brokkr_kitba R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") print("READINGS", R["readings"], flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index 5659698..e86c3ee 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -47,6 +47,10 @@ RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived wh def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) @@ -421,7 +425,7 @@ for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: bpy.data.objects.remove(hull) R["ok"] = all(c["ok"] for c in R["checks"]) -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index afe1e82..ead0f7d 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -125,7 +125,7 @@ "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", - "observedAt": "2026-12-01T01:10:29.202522+00:00" + "observedAt": "2026-12-02T11:45:23.730020+00:00" } }, { @@ -231,21 +231,21 @@ "Ball" ], "explainedByLight": { - "before": 0.9718638595466577, - "after": 0.0005166823179215685 + "before": 0.971864311889026, + "after": 0.0005166699920249318 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166067038538378, + "upDownLuminanceRatio": 1.0166056941702677, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857558709602762, - "median": 1.457103285957073, - "max": 3.0649151172981792, + "min": 0.9857550779013501, + "median": 1.4570952973825366, + "max": 3.0649084607569628, "clamped": 0.0 } } @@ -374,21 +374,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085393, - "after": 0.028075104342772272 + "before": 0.9999597575085379, + "after": 0.028075104345557378 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767503613, - "occlusionCorrelation": 0.40471079036691976 + "upDownLuminanceRatio": 0.9999964767501422, + "occlusionCorrelation": 0.4047107903549991 }, "gain": { - "min": 0.9999809983875252, - "median": 1.0000990920451596, - "max": 5.493916964800697, + "min": 0.9999809983874741, + "median": 1.0000990920454487, + "max": 5.493916964791895, "clamped": 0.0 } }, @@ -572,15 +572,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748396336225e-08, + "X": 1.8120748391154895e-08, "Y": 0.1508370330678463, - "Z": 1.8363068583553207e-08 + "Z": 1.836306858436306e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218171415895767e-09 + -1.8218169195449718e-09 ], "knobReach": 3.0, "parent": "Block.body" @@ -653,72 +653,6 @@ "name": "a bound miss is denied by Brokkr's table before the operator runs", "ok": true, "detail": "max_gain must be between 1 and 8." - }, - { - "name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides", - "ok": true, - "detail": { - "polygons": 28426, - "polygonsAfter": 28420, - "turned": null, - "againstBefore": 388, - "againstAfter": 387, - "changes": { - "welded": 6437, - "facesCollapsedByWeld": 2, - "degenerateFacesRemoved": 4, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } - }, - { - "name": "hull sub.glb: repair turns no face and keeps the shading normals' sides", - "ok": true, - "detail": { - "polygons": 10406, - "polygonsAfter": 10406, - "turned": 0, - "againstBefore": 64, - "againstAfter": 64, - "changes": { - "welded": 2454, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 0, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } - }, - { - "name": "hull third.glb: repair turns no face and keeps the shading normals' sides", - "ok": true, - "detail": { - "polygons": 23341, - "polygonsAfter": 23340, - "turned": null, - "againstBefore": 189, - "againstAfter": 189, - "changes": { - "welded": 3810, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 1, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } } ], "hostErrors": [], @@ -744,21 +678,21 @@ "Ball" ], "explainedByLight": { - "before": 0.9718638595466577, - "after": 0.0005166823179215685 + "before": 0.971864311889026, + "after": 0.0005166699920249318 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166067038538378, + "upDownLuminanceRatio": 1.0166056941702677, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857558709602762, - "median": 1.457103285957073, - "max": 3.0649151172981792, + "min": 0.9857550779013501, + "median": 1.4570952973825366, + "max": 3.0649084607569628, "clamped": 0.0 } }, @@ -804,21 +738,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085393, - "after": 0.028075104342772272 + "before": 0.9999597575085379, + "after": 0.028075104345557378 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767503613, - "occlusionCorrelation": 0.40471079036691976 + "upDownLuminanceRatio": 0.9999964767501422, + "occlusionCorrelation": 0.4047107903549991 }, "gain": { - "min": 0.9999809983875252, - "median": 1.0000990920451596, - "max": 5.493916964800697, + "min": 0.9999809983874741, + "median": 1.0000990920454487, + "max": 5.493916964791895, "clamped": 0.0 } }, @@ -880,15 +814,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748396336225e-08, + "X": 1.8120748391154895e-08, "Y": 0.1508370330678463, - "Z": 1.8363068583553207e-08 + "Z": 1.836306858436306e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218171415895767e-09 + -1.8218169195449718e-09 ], "knobReach": 3.0, "parent": "Block.body" @@ -908,61 +842,6 @@ "inkInsideBefore": 192, "inkInsideAfter": 0 }, - "hulls": { - "fourth.glb": { - "polygons": 28426, - "polygonsAfter": 28420, - "turned": null, - "againstBefore": 388, - "againstAfter": 387, - "changes": { - "welded": 6437, - "facesCollapsedByWeld": 2, - "degenerateFacesRemoved": 4, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - }, - "sub.glb": { - "polygons": 10406, - "polygonsAfter": 10406, - "turned": 0, - "againstBefore": 64, - "againstAfter": 64, - "changes": { - "welded": 2454, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 0, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - }, - "third.glb": { - "polygons": 23341, - "polygonsAfter": 23340, - "turned": null, - "againstBefore": 189, - "againstAfter": 189, - "changes": { - "welded": 3810, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 1, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } - }, + "hulls": {}, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 09c4396..a3c665c 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -56,6 +56,10 @@ T0 = time.time() def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) @@ -332,7 +336,7 @@ check("and leaves the skin as body made it, with no chain bones", ball_weights() and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) R["ok"] = all(c["ok"] for c in R["checks"]) -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 9cc1424..91255bf 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -197,8 +197,8 @@ }, { "bone": "spine_04", - "before": 0.106817, - "after": 0.074496 + "before": 0.107081, + "after": 0.07411 } ], "shrunkMax": 0.6571, @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-l9ustbpi\\whale.glb (301188 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-s67r7hee\\whale.glb (301168 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -630,8 +630,8 @@ }, { "bone": "spine_04", - "before": 0.106817, - "after": 0.074496 + "before": 0.107081, + "after": 0.07411 } ], "shrunkMax": 0.6571, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index ab0d8c5..3faf4d3 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1558,6 +1558,34 @@ class SheetTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"): core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]}) + def test_fold_depths_are_the_narrower_facets_first_row_over_the_tangent(self): + """A ridge of two flat facets 1.0 and 0.3 wide, each tilted 45 degrees: the crease's fold depth is + (0.3 / 2^levels) / tan 45, the narrower facet's (F1: the wider facet's reach reads 0.25 at levels 2); the + facets fall away from their normals, a ridge, and turned over they are a valley; coplanar facets never fold.""" + h = math.sqrt(0.5) + + def wedge(sign, flat=False): + return core.sheet({"rings": [[[-h, y, 0.0 if flat else -sign * h], [0.0, y, 0.0], [0.3 * h, y, 0.0 if flat else -sign * 0.3 * h]] for y in (0.0, 0.5, 1.0)], + "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]}) + + pairs, depths, ridges, weights = core.fold_depths(wedge(1), 2) + crease = [k for k, pair in enumerate(pairs.tolist()) if pair in ([1, 4], [4, 7])] + self.assertEqual(len(pairs), 4) # the two crease edges and the middle ring's edge on each facet: an edge of the rim has one quad and no fold + self.assertEqual(len(crease), 2) + for k in crease: + self.assertAlmostEqual(depths[k], 0.075, places=12) + self.assertTrue(ridges[k]) + self.assertEqual(weights[k], 1.0) + self.assertTrue(all(math.isinf(depths[k]) and weights[k] == 0.0 for k in range(len(pairs)) if k not in crease)) # an edge inside a flat facet + self.assertAlmostEqual(core.fold_depths(wedge(1), 3)[1][crease[0]], 0.0375, places=12) # a level more halves the first row + valley = core.fold_depths(wedge(-1), 2) + self.assertAlmostEqual(valley[1][crease[0]], 0.075, places=12) + self.assertFalse(valley[2][crease[0]]) + self.assertTrue(np.isinf(core.fold_depths(wedge(1, flat=True), 2)[1]).all()) + steep = core.sheet({"rings": [[[-0.5, y, -math.sqrt(0.75)], [0.0, y, 0.0], [0.5, y, -math.sqrt(0.75)]] for y in (0.0, 1.0)]}) # facets 60 degrees off level, no crease stated + self.assertAlmostEqual(core.fold_depths(steep, 1)[1][0], 0.5 / math.tan(math.radians(60)), places=12) + self.assertEqual(core.fold_depths(steep, 1)[3][0], 0.0) + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", From d3c68edf79ee10952557a9416fc98a451a009532 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 13:29:46 +0100 Subject: [PATCH 09/10] live kitbash, kitbash_assembly, kitbash_pose, mesh_polish, rig: the checks run inside one try An error raised between checks is a failed check that names the check before it; the checks are printed and the result file written whatever happened, and the exit is 1 with or without --python-exit-code. A rig.py copy with a raise after 35 checks, launched bare: exit 1, 35 ok and 1 FAIL printed, result file written (was exit 0 and no CHECK line). Finding: aetheria-release:finding:cut-kit-faceted-shell.s3.midsuite-raise-hides-checks Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash.py | 341 +++--- .../blender/tests/live/kitbash_assembly.py | 1018 +++++++++-------- surfaces/blender/tests/live/kitbash_pose.py | 262 ++--- surfaces/blender/tests/live/mesh_polish.py | 610 +++++----- .../tests/live/mesh_polish.result.json | 66 +- surfaces/blender/tests/live/rig.py | 334 +++--- surfaces/blender/tests/live/rig.result.json | 2 +- 7 files changed, 1332 insertions(+), 1301 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index d3d94e2..6b03a2e 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -5,13 +5,16 @@ assignMaterial, set_params, report, the refusals, and exportGltf. Not part of th blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses -without them). Writes .result.json and exits 1 when a check failed. +without them). Writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. """ import importlib.util import json import math import os import sys +import traceback import tempfile import types from pathlib import Path @@ -81,185 +84,189 @@ def extent(obj, axis=2): return float(co[:, axis].max() - co[:, axis].min()) -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS]) +try: + check("the kitbash rows load as host actions with no errors", not R["hostErrors"] + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS]) -# --- describe --------------------------------------------------------------------------------------------------------- -kit = core.load_kit("mechanical") -receipt, described = send("brokkr_kitbash.describe") -names = [p["name"] for p in described["parts"]] if described else [] -check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 - and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) -receipt, one = send("brokkr_kitbash.describe", part="actuator") -check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] - and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"] - and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one) -check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)]) + # --- describe --------------------------------------------------------------------------------------------------------- + kit = core.load_kit("mechanical") + receipt, described = send("brokkr_kitbash.describe") + names = [p["name"] for p in described["parts"]] if described else [] + check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 + and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) + receipt, one = send("brokkr_kitbash.describe", part="actuator") + check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] + and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"] + and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one) + check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)]) -# --- place every part at default ----------------------------------------------------------------------------------------- -placed = {} -for index, name in enumerate(names): - receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}") - obj = bpy.data.objects.get(f"P_{name}") - reference = core.build(kit["parts"][name]) - faces = len(obj.data.polygons) if obj else -1 - clean = obj is not None and not obj.data.validate(verbose=False) - flat = np.zeros(max(faces, 0), dtype=bool) - if obj: - obj.data.attributes["sharp_face"].data.foreach_get("value", flat) - crease = obj.data.attributes.get("sharp_edge") if obj else None - creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) - if crease: - crease.data.foreach_get("value", creased) - marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None - check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", - marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) - bevel = obj.modifiers.get("Kit Bevel") if obj else None - evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 - placed[name] = report - check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report - and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count - and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0] - and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6), - [receipt["message"], faces, len(reference.counts), clean]) - check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None - and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE" - and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces]) - check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None - and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] - and report["sockets"] == core.socket_rows(reference.sockets), report) -check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) + # --- place every part at default ----------------------------------------------------------------------------------------- + placed = {} + for index, name in enumerate(names): + receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}") + obj = bpy.data.objects.get(f"P_{name}") + reference = core.build(kit["parts"][name]) + faces = len(obj.data.polygons) if obj else -1 + clean = obj is not None and not obj.data.validate(verbose=False) + flat = np.zeros(max(faces, 0), dtype=bool) + if obj: + obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + crease = obj.data.attributes.get("sharp_edge") if obj else None + creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) + if crease: + crease.data.foreach_get("value", creased) + marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None + check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", + marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) + bevel = obj.modifiers.get("Kit Bevel") if obj else None + evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 + placed[name] = report + check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report + and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count + and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0] + and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6), + [receipt["message"], faces, len(reference.counts), clean]) + check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None + and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE" + and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces]) + check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None + and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] + and report["sockets"] == core.socket_rows(reference.sockets), report) + check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) -# --- set_params keeps what is not derived -------------------------------------------------------------------------------- -reducer = bpy.data.objects["P_reducer"] -send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") -creased = np.zeros(len(reducer.data.edges), dtype=bool) -reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) -rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] -check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", - len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 - and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) -tank = bpy.data.objects["P_tank"] -send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) -send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) -send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate") -before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, - "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], - "faces": len(tank.data.polygons)} -receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8") -after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, - "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], - "faces": len(tank.data.polygons)} -check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6 - and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]]) -check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate" - and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"] - and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after]) -check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"] - == {"radius": 0.22, "length": 1.8, "segments": 24}, grown) -receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12") -check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12} - and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts), - [wide and wide["params"], tank.modifiers["Kit Bevel"].width]) + # --- set_params keeps what is not derived -------------------------------------------------------------------------------- + reducer = bpy.data.objects["P_reducer"] + send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") + creased = np.zeros(len(reducer.data.edges), dtype=bool) + reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) + rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] + check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 + and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) + tank = bpy.data.objects["P_tank"] + send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) + send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) + send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate") + before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} + receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8") + after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} + check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6 + and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]]) + check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate" + and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"] + and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after]) + check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"] + == {"radius": 0.22, "length": 1.8, "segments": 24}, grown) + receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12") + check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12} + and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts), + [wide and wide["params"], tank.modifiers["Kit Bevel"].width]) -# --- report: sockets in the world ------------------------------------------------------------------------------------------- -send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) -receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones -bpy.context.view_layer.update() -worst, listed = 0.0, [] -for entry in (reported or {}).get("parts", []): - obj = bpy.data.objects[entry["object"]] - listed.append(entry["object"]) - local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets - world = np.array(obj.matrix_world) - for socket, mine in zip(entry["sockets"], local): - worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max())) -check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted" - and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst]) -receipt, single = send("brokkr_kitbash.report", object_name="P_tank") -tank_world = np.array(tank.matrix_world) -check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1 - and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons) - and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 - and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) + # --- report: sockets in the world ------------------------------------------------------------------------------------------- + send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) + receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones + bpy.context.view_layer.update() + worst, listed = 0.0, [] + for entry in (reported or {}).get("parts", []): + obj = bpy.data.objects[entry["object"]] + listed.append(entry["object"]) + local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets + world = np.array(obj.matrix_world) + for socket, mine in zip(entry["sockets"], local): + worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max())) + check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted" + and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst]) + receipt, single = send("brokkr_kitbash.report", object_name="P_tank") + tank_world = np.array(tank.matrix_world) + check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1 + and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons) + and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 + and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) -# --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- -strut = bpy.data.objects["P_strut"] -send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) -strut.data.materials.append(bpy.data.materials.new("Pin Steel")) -PINS = 2 # the strut's third shape: the repeat of two pins -was = core.build(kit["parts"]["strut"]) -strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) -receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") -now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) -index = np.zeros(len(strut.data.polygons), dtype=np.int32) -strut.data.polygons.foreach_get("material_index", index) -check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" - and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) - and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) + # --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- + strut = bpy.data.objects["P_strut"] + send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) + strut.data.materials.append(bpy.data.materials.new("Pin Steel")) + PINS = 2 # the strut's third shape: the repeat of two pins + was = core.build(kit["parts"]["strut"]) + strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) + receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") + now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) + index = np.zeros(len(strut.data.polygons), dtype=np.int32) + strut.data.polygons.foreach_get("material_index", index) + check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" + and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) + and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) -# --- refusals leave the scene as it was -------------------------------------------------------------------------------------- -bpy.ops.mesh.primitive_cube_add() -bpy.context.active_object.name = "Plain" -twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params -twin.name = "P_vent_twin" -bpy.context.scene.collection.objects.link(twin) -send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) -send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) + # --- refusals leave the scene as it was -------------------------------------------------------------------------------------- + bpy.ops.mesh.primitive_cube_add() + bpy.context.active_object.name = "Plain" + twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params + twin.name = "P_vent_twin" + bpy.context.scene.collection.objects.link(twin) + send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) + send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) -def scene_state(): - return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes), - {o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects}) + def scene_state(): + return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes), + {o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects}) -state = scene_state() -refusals = [ - ("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"), - ("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"), - ("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"), - ("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"), - ("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"), - ("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"), - ("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"), - ("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"), - ("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"), - ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), - ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), - ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), - ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), - ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), - ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), - ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), - ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), - ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), - ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), -] -for label, action, fields, expected in refusals: - receipt, _ = send(action, **fields) - check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, - [receipt["status"], receipt["message"]]) + state = scene_state() + refusals = [ + ("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"), + ("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"), + ("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"), + ("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"), + ("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"), + ("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"), + ("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"), + ("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"), + ("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"), + ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), + ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), + ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), + ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), + ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), + ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), + ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), + ] + for label, action, fields, expected in refusals: + receipt, _ = send(action, **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) -bpy.data.objects.remove(twin) -send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) -send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) -receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") -check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone - and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) -receipt, whole = send("brokkr_kitbash.report") -check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) + bpy.data.objects.remove(twin) + send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) + send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) + receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") + check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone + and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) + receipt, whole = send("brokkr_kitbash.report") + check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) -# --- export --------------------------------------------------------------------------------------------------------------- -receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) -glb = WORK / "kit.glb" -meshes = -1 -if glb.is_file(): - blob = glb.read_bytes() - meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) -check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) + # --- export --------------------------------------------------------------------------------------------------------------- + receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) + glb = WORK / "kit.glb" + meshes = -1 + if glb.is_file(): + blob = glb.read_bytes() + meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) + check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) + + R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} + for name, report in placed.items() if report} +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) -R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} - for name, report in placed.items() if report} R["ok"] = all(c["ok"] for c in R["checks"]) for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 805e576..33b580e 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -6,7 +6,9 @@ of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses -without them). is an absolute path; writes .result.json and exits 1 when a check failed. +without them). is an absolute path; writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. An Exact Boolean costs a few tenths of a second a part and evaluation (docs/kitbash.md), so few parts are cut here: the tank, a tee and three plates. Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the @@ -19,6 +21,7 @@ import math import os import re import sys +import traceback import tempfile import types from pathlib import Path @@ -183,535 +186,538 @@ def evaluated(obj): return row, [m.name if m else None for m in shown.data.materials] -rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], rows, OPERATORS]) +try: + rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] + check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], rows, OPERATORS]) -# --- attach ------------------------------------------------------------------------------------------------------------- -tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 -tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7]) -nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0]) -spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0]) -wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14 -radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) -send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) -receipt, report = send("brokkr_kitbash.report", object_name="Tank") -check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None - and report["parts"][0]["baked"] is False, report) + # --- attach ------------------------------------------------------------------------------------------------------------- + tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 + tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7]) + nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0]) + spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0]) + wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14 + radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) + send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) + receipt, report = send("brokkr_kitbash.report", object_name="Tank") + check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None + and report["parts"][0]["baked"] is False, report) -receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) -check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" - and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)) - and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0) - and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"], - [receipt["message"], dict(nozzle.items())]) -gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) -check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"])) -check("attach reports the child: its connection holds, and its sockets are the seated world frames", report - and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True} - and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle" - and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report) -check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") -check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED - and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL - and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]]) + receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) + check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" + and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)) + and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0) + and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"], + [receipt["message"], dict(nozzle.items())]) + gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) + check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"])) + check("attach reports the child: its connection holds, and its sockets are the seated world frames", report + and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True} + and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle" + and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report) + check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") + check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]]) -refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"}, - "'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types") -refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, - "mate at equal sizes") -refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, - "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") -refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"}, - "Socket 'a' of 'Tee' is occupied (by 'Tank')") -refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"}, - "'Nozzle' is below 'Tank'") -refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, - "'Nozzle' has a parent, 'Tee'") -refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"}, - "cannot be attached to itself") -refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"}, - "'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c") -refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"}, - "part 'nozzle' has no socket 'throat'") -refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"}, - "'Plain' is not a kit part") -refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, - "'Plain' is not a kit part") -refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached (it has no kit_socket property) and states no closure") -send("brokkr_kitbash.detach", object_name="Tee") -send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) -refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, - "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") -send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") -receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0) -check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"}, + "'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types") + refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "mate at equal sizes") + refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") + refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"}, + "Socket 'a' of 'Tee' is occupied (by 'Tank')") + refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"}, + "'Nozzle' is below 'Tank'") + refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "'Nozzle' has a parent, 'Tee'") + refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"}, + "cannot be attached to itself") + refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"}, + "'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c") + refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"}, + "part 'nozzle' has no socket 'throat'") + refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"}, + "'Plain' is not a kit part") + refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, + "'Plain' is not a kit part") + refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached (it has no kit_socket property) and states no closure") + send("brokkr_kitbash.detach", object_name="Tee") + send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) + refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") + send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") + receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0) + check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) -# --- set_params seats what is attached again ---------------------------------------------------------------------------------- -was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")} -receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8") -moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was} -port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z -check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", - receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0 - and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")), - [receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()]) -check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED - and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")]) -refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"}, - "'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)") -refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"}, - "'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)") -receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6") -check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED - and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + # --- set_params seats what is attached again ---------------------------------------------------------------------------------- + was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")} + receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8") + moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was} + port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z + check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", + receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0 + and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")), + [receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()]) + check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")]) + refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)") + refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)") + receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6") + check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) -# a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod -lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054 -strut = place("Strut", "strut", "width=0.09") -ram = place("Ram", "actuator") -send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0) -send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b") -base = frame(ram, "base") -receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5") -back = frame(ram, "base")[:3, 3] - base[:3, 3] -check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", - reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) - and reading("carried", np.abs(back + base[:3, 1] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) # a pivot's y is the part's axis -tip = frame(strut, "end_b") -receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") -check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" - and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0] - and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED - and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, - [receipt["message"], connection("Strut"), connection("Ram")]) + # a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod + lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054 + strut = place("Strut", "strut", "width=0.09") + ram = place("Ram", "actuator") + send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0) + send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b") + base = frame(ram, "base") + receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5") + back = frame(ram, "base")[:3, 3] - base[:3, 3] + check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", + reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) + and reading("carried", np.abs(back + base[:3, 1] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) # a pivot's y is the part's axis + tip = frame(strut, "end_b") + receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") + check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" + and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0] + and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED + and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, + [receipt["message"], connection("Strut"), connection("Ram")]) -# --- a closure: a brace from a second bracket closes on the leg's rod pin ------------------------------------------------------------ -hull = place("Hull", "tank", "radius=0.3; length=1.2", location=[6.0, 0.0, 2.0], rotation=[0.0, math.pi, 0.4]) # lug size 0.09 -upper, lower = place("Upper", "bracket"), place("Lower", "bracket") # pin 0.054, plate 0.09 -send("brokkr_kitbash.attach", object_name="Upper", socket="mount", parent_name="Hull", parent_socket="lug_b") -send("brokkr_kitbash.attach", object_name="Lower", socket="mount", parent_name="Hull", parent_socket="lug_a", roll=180.0) # turned half: its pin face looks back at Upper's -leg, brace, tie = place("Leg", "actuator"), place("Brace", "strut", "width=0.09; length=1.1"), place("Tie", "strut", "width=0.09") -p1, p2 = frame(upper, "pivot"), frame(lower, "pivot") -check("a bracket turned half on the next lug pins on the first one's plane, facing it", abs((p2[:3, 3] - p1[:3, 3]) @ p1[:3, 2]) < SEATED - and np.abs(p1[:3, 2] + p2[:3, 2]).max() < SEATED, [p1.tolist(), p2.tolist()]) -span = {name: core.build(kit["parts"][part], given) for name, part, given in (("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": 1.1}))} -a = next(s for s in span["leg"].sockets if s["name"] == "rod_end")["matrix"][2, 3] - next(s for s in span["leg"].sockets if s["name"] == "base")["matrix"][2, 3] -b = next(s for s in span["brace"].sockets if s["name"] == "end_b")["matrix"][2, 3] - next(s for s in span["brace"].sockets if s["name"] == "end_a")["matrix"][2, 3] -d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) -corner = math.acos((a * a + d * d - b * b) / (2 * a * d)) # the law of cosines: the angle at the upper pin between the hull and the leg -knee = p1[:3, 3] + a * (math.cos(corner) * (p2[:3, 3] - p1[:3, 3]) / d + math.sin(corner) * frame(hull, "lug_b")[:3, 2]) + # --- a closure: a brace from a second bracket closes on the leg's rod pin ------------------------------------------------------------ + hull = place("Hull", "tank", "radius=0.3; length=1.2", location=[6.0, 0.0, 2.0], rotation=[0.0, math.pi, 0.4]) # lug size 0.09 + upper, lower = place("Upper", "bracket"), place("Lower", "bracket") # pin 0.054, plate 0.09 + send("brokkr_kitbash.attach", object_name="Upper", socket="mount", parent_name="Hull", parent_socket="lug_b") + send("brokkr_kitbash.attach", object_name="Lower", socket="mount", parent_name="Hull", parent_socket="lug_a", roll=180.0) # turned half: its pin face looks back at Upper's + leg, brace, tie = place("Leg", "actuator"), place("Brace", "strut", "width=0.09; length=1.1"), place("Tie", "strut", "width=0.09") + p1, p2 = frame(upper, "pivot"), frame(lower, "pivot") + check("a bracket turned half on the next lug pins on the first one's plane, facing it", abs((p2[:3, 3] - p1[:3, 3]) @ p1[:3, 2]) < SEATED + and np.abs(p1[:3, 2] + p2[:3, 2]).max() < SEATED, [p1.tolist(), p2.tolist()]) + span = {name: core.build(kit["parts"][part], given) for name, part, given in (("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": 1.1}))} + a = next(s for s in span["leg"].sockets if s["name"] == "rod_end")["matrix"][2, 3] - next(s for s in span["leg"].sockets if s["name"] == "base")["matrix"][2, 3] + b = next(s for s in span["brace"].sockets if s["name"] == "end_b")["matrix"][2, 3] - next(s for s in span["brace"].sockets if s["name"] == "end_a")["matrix"][2, 3] + d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) + corner = math.acos((a * a + d * d - b * b) / (2 * a * d)) # the law of cosines: the angle at the upper pin between the hull and the leg + knee = p1[:3, 3] + a * (math.cos(corner) * (p2[:3, 3] - p1[:3, 3]) / d + math.sin(corner) * frame(hull, "lug_b")[:3, 2]) -def roll_to(pin, toward): - """The roll that points a pinned member's axis (its socket's y) from this pin toward a point in the pin's plane.""" - toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) - return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) + def roll_to(pin, toward): + """The roll that points a pinned member's axis (its socket's y) from this pin toward a point in the pin's plane.""" + toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) + return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) -def closure_of(name): - receipt, report = send("brokkr_kitbash.report", object_name=name) - return report["parts"][0]["closure"] if report else {"error": receipt["message"]} + def closure_of(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["closure"] if report else {"error": receipt["message"]} -def closure_row(name): - return closure_of(name) or {} + def closure_row(name): + return closure_of(name) or {} -def without_closures(state): - return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] + def without_closures(state): + return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] -CLOSING = {"object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} -send("brokkr_kitbash.attach", object_name="Leg", socket="base", parent_name="Upper", parent_socket="pivot", roll=roll_to(p1, knee)) -send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee) + 1.0) -apart = core.closure_residual(np.array(leg.matrix_world), next(s for s in span["leg"].sockets if s["name"] == "rod_end"), - np.array(brace.matrix_world), next(s for s in span["brace"].sockets if s["name"] == "end_b")) -state = scene_state() -receipt, _ = send("brokkr_kitbash.close", **CLOSING) -named = re.search(r"Socket 'end_b' of 'Brace' and socket 'rod_end' of 'Leg' stand (\S+) m apart: place them so they meet", str(receipt["message"])) -check("refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", receipt["status"] != "accepted" - and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) -send("brokkr_kitbash.detach", object_name="Brace") -send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) -# close-tolerance: the brace moved NUDGE (3.2e-4) off its seat. close accepts up to HELD, 1e-5; least claimed mutant 5e-4 (N2, 50 times -# HELD); NUDGE is 32 times the one and 0.64 of the other, as for the connection's own check below. -seat_was = np.array(brace.matrix_basis)[:3, 3] -send("setObjectTransform", targetObjectName="Brace", location=(seat_was + np.array(lower.matrix_world)[:3, :3].T @ [0.0, 0.0, NUDGE]).tolist()) -state = scene_state() -receipt, _ = send("brokkr_kitbash.close", **CLOSING) -named = re.search(r"stand (\S+) m apart", str(receipt["message"])) -check("refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", receipt["status"] != "accepted" and named - and abs(reading("close nudged", float(named.group(1))) - NUDGE) < 0.1 * NUDGE and scene_state() == state, receipt["message"]) -send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") # seats it again -state = scene_state() -receipt, report = send("brokkr_kitbash.close", **CLOSING) -check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" - and reading("seated", seated(brace, "end_b", leg, "rod_end")) < SEATED and without_closures(scene_state()) == without_closures(state) - and (brace["kit_close_socket"], brace["kit_close_to"], brace["kit_close_to_socket"]) == ("end_b", leg, "rod_end") - and sorted(k for k in brace.keys() if k.startswith("kit_close")) == ["kit_close_socket", "kit_close_to", "kit_close_to_socket"] - and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) -check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" - and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} - and reading("closed", report["closure"]["residual"]) <= 1e-5 and report["closure"]["reason"] is None and held(report) and closure_of("Brace") == report["closure"] - and closure_of("Leg") is None, report) -refused("a second closure on a part that states one", "brokkr_kitbash.close", - {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") -refused("close on a socket a closure holds", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end"}, - "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") -refused("close on the closing socket itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Brace", "other_socket": "end_b"}, - "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") -refused("close on a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "base"}, - "Socket 'base' of 'Leg' is occupied (by 'Upper')") -refused("close by a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Leg", "socket": "base", "other_name": "Tie", "other_socket": "end_a"}, - "Socket 'base' of 'Leg' is occupied (by 'Upper')") -refused("attach onto a socket a closure holds", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Leg", "parent_socket": "rod_end"}, - "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") -refused("attach onto the closing socket", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Brace", "parent_socket": "end_b"}, - "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") -refused("close of a part on itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Tie", "other_socket": "end_b"}, "'Tie' cannot close on itself") -refused("close of sockets that may not mate", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Hull", "other_socket": "lug_a_back"}, - "'Tie' closing on 'Hull': socket 'end_a' (pivot, size 0.054) and parent socket 'lug_a_back' (mount, size 0.09) are of different types") -refused("close of two sockets that are apart", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "m apart: place them so they meet") -refused("close on a mesh that is not a kit part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Plain", "other_socket": "a"}, "'Plain' is not a kit part") -refused("close of a socket the part does not have", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_c", "other_name": "Leg", "other_socket": "rod_end_back"}, - "part 'strut' has no socket 'end_c'") -was = np.array(brace.matrix_world) -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -found = closure_row("Brace") -check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", - receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None - and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) - and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") -check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" - and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) -# closures-omitted: a second closure, named to sort first, far from the leg; then a receipt with room for one row. Mutant N5 (never -# omit) lists two rows; rows by name alone would keep Aa_Loose and drop the one this call opened. -anchor, loose = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]), place("Aa_Loose", "strut", "width=0.09") -meet = Matrix((np.array(anchor.matrix_world) @ core.mate(next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_b"), - next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_a"), 40.0)).tolist()) -send("setObjectTransform", targetObjectName="Aa_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) -receipt, report = send("brokkr_kitbash.close", object_name="Aa_Loose", socket="end_a", other_name="Aa_Anchor", other_socket="end_b") -check("a loose part placed to meet a socket closes on it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -ROWS = [{"part": "Brace", "to": "Leg", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] -check("set_params lists the closures its own part is an end of first, then the rest", receipt["status"] == "accepted" and report["closures"] == ROWS - and "closuresOmitted" not in report, report and report.get("closures")) -addon = sys.modules["brokkr_kitbash"] -limit = addon.REPORT_LIMIT -addon.REPORT_LIMIT = len(json.dumps({k: v for k, v in report.items() if k != "closures"}, separators=(",", ":"))) + 40 + len(json.dumps(ROWS[0], separators=(",", ":"))) + 1 -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -addon.REPORT_LIMIT = limit -check("with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", receipt["status"] == "accepted" - and report["closures"] == ROWS[:1] and report.get("closuresOmitted") == 1 and np.array_equal(np.array(brace.matrix_world), was), report and [report.get("closures"), report.get("closuresOmitted")]) -receipt, report = send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") -check("and a closure another part's set_params opened comes before one that holds", receipt["status"] == "accepted" - and report["closures"] == [{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}, {"part": "Brace", "to": "Leg", "holds": False}], report and report.get("closures")) -send("brokkr_kitbash.detach", object_name="Aa_Loose") -send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") -leg.scale = (1.0001, 1.0, 1.0) -bpy.context.view_layer.update() -found = closure_row("Brace") -leg.scale = (1.0, 1.0, 1.0) -bpy.context.view_layer.update() -check("a closure on a part scaled by hand reads broken, naming the part and why, not gone", found.get("to") == "Leg" and found.get("holds") is False and found.get("residual") is None - and "'Leg' is scaled, mirrored or sheared" in str(found.get("reason")) and closure_row("Brace").get("holds") is True, found) -twin = brace.copy() # as Shift-D leaves it: a second part stating the same closure -twin.data = brace.data.copy() -twin.name = "Brace_twin" -bpy.context.scene.collection.objects.link(twin) -found, other = closure_row("Brace"), closure_row("Brace_twin") -check("two parts that state a closure on one socket both read not held, each naming the other", found.get("holds") is False and other.get("holds") is False - and "is also closed on by 'Brace_twin'" in str(found.get("reason")) and "is also closed on by 'Brace'" in str(other.get("reason")), [found, other]) -tie["keeper"] = twin # something still points at the copy, so Delete leaves it in the file with its closure properties -with bpy.context.temp_override(selected_objects=[twin], active_object=twin): - bpy.ops.object.delete() -check("and with the copy deleted the closure holds again, though the copy is still in the file stating its own", closure_row("Brace").get("holds") is True - and bpy.data.objects.get("Brace_twin") is not None and "kit_close_to" in bpy.data.objects["Brace_twin"], closure_of("Brace")) -del tie["keeper"] -bpy.data.objects.remove(bpy.data.objects["Brace_twin"]) -refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, - "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") -refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, - "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.06) and parent socket 'rod_end' (pivot, size 0.054)") -receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") -check("set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", - receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"]["holds"] is False - and held(report) and 0.1 / math.sqrt(3) - 1e-5 <= report["closure"]["residual"] <= 0.1 + 1e-5, [receipt["message"], report and report["closure"]]) -send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") -before = np.array(brace.matrix_world) -receipt, report = send("brokkr_kitbash.detach", object_name="Brace") -check("detach clears the brace's closure with its connection, and it stays where it stood", receipt["status"] == "accepted" and report and report["closure"] is None - and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None - and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) -receipt, report = send("brokkr_kitbash.close", **CLOSING) -check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) -leg.name = "Shin" -found = closure_row("Brace") -check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) -leg.name = "Leg" -send("brokkr_kitbash.detach", object_name="Leg") -homes = list(leg.users_collection) -for home in homes: - home.objects.unlink(leg) -found = closure_row("Brace") -check("a closure on a part unlinked from every collection reads to null, holds false, with the reason", found.get("to", 0) is None and found.get("holds") is False - and "gone" in str(found.get("reason")) and "Leg" in bpy.data.objects, found) -for home in homes: - home.objects.link(leg) -check("and holds again once the part is linked back", closure_row("Brace").get("holds") is True, closure_of("Brace")) -with bpy.context.temp_override(selected_objects=[leg], active_object=leg): - bpy.ops.object.delete() # the ordinary Delete: the closure's pointer keeps the object in the file as an orphan -found = closure_row("Brace") -check("a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", found.get("to", 0) is None - and found.get("holds") is False and found.get("residual", 0) is None and bpy.data.objects.get("Leg") is not None and brace.get("kit_close_to") is not None, [found, list(bpy.data.objects.keys())]) -refused("close onto a deleted part that is still in the file", "brokkr_kitbash.close", - {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Leg' is in no collection") -if "Leg" in bpy.data.objects: - bpy.data.objects.remove(bpy.data.objects["Leg"]) -found = closure_row("Brace") -receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") -check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} - and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) -before = np.array(brace.matrix_world) -receipt, report = send("brokkr_kitbash.detach", object_name="Brace") -check("detach of a part that states only a closure clears it and leaves the part where it stood", receipt["status"] == "accepted" and report["closure"] is None - and not [k for k in brace.keys() if k.startswith("kit_close")] and np.array_equal(np.array(brace.matrix_world), before), [receipt["message"], dict(brace.items())]) -receipt, report = send("brokkr_kitbash.attach", object_name="Tie", socket="end_a", parent_name="Brace", parent_socket="end_b") -check("and the socket the closure held is free again", receipt["status"] == "accepted" and held(report), receipt["message"]) + CLOSING = {"object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} + send("brokkr_kitbash.attach", object_name="Leg", socket="base", parent_name="Upper", parent_socket="pivot", roll=roll_to(p1, knee)) + send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee) + 1.0) + apart = core.closure_residual(np.array(leg.matrix_world), next(s for s in span["leg"].sockets if s["name"] == "rod_end"), + np.array(brace.matrix_world), next(s for s in span["brace"].sockets if s["name"] == "end_b")) + state = scene_state() + receipt, _ = send("brokkr_kitbash.close", **CLOSING) + named = re.search(r"Socket 'end_b' of 'Brace' and socket 'rod_end' of 'Leg' stand (\S+) m apart: place them so they meet", str(receipt["message"])) + check("refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", receipt["status"] != "accepted" + and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) + send("brokkr_kitbash.detach", object_name="Brace") + send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) + # close-tolerance: the brace moved NUDGE (3.2e-4) off its seat. close accepts up to HELD, 1e-5; least claimed mutant 5e-4 (N2, 50 times + # HELD); NUDGE is 32 times the one and 0.64 of the other, as for the connection's own check below. + seat_was = np.array(brace.matrix_basis)[:3, 3] + send("setObjectTransform", targetObjectName="Brace", location=(seat_was + np.array(lower.matrix_world)[:3, :3].T @ [0.0, 0.0, NUDGE]).tolist()) + state = scene_state() + receipt, _ = send("brokkr_kitbash.close", **CLOSING) + named = re.search(r"stand (\S+) m apart", str(receipt["message"])) + check("refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", receipt["status"] != "accepted" and named + and abs(reading("close nudged", float(named.group(1))) - NUDGE) < 0.1 * NUDGE and scene_state() == state, receipt["message"]) + send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") # seats it again + state = scene_state() + receipt, report = send("brokkr_kitbash.close", **CLOSING) + check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" + and reading("seated", seated(brace, "end_b", leg, "rod_end")) < SEATED and without_closures(scene_state()) == without_closures(state) + and (brace["kit_close_socket"], brace["kit_close_to"], brace["kit_close_to_socket"]) == ("end_b", leg, "rod_end") + and sorted(k for k in brace.keys() if k.startswith("kit_close")) == ["kit_close_socket", "kit_close_to", "kit_close_to_socket"] + and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) + check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" + and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} + and reading("closed", report["closure"]["residual"]) <= 1e-5 and report["closure"]["reason"] is None and held(report) and closure_of("Brace") == report["closure"] + and closure_of("Leg") is None, report) + refused("a second closure on a part that states one", "brokkr_kitbash.close", + {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") + refused("close on a socket a closure holds", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") + refused("close on the closing socket itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Brace", "other_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") + refused("close on a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "base"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") + refused("close by a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Leg", "socket": "base", "other_name": "Tie", "other_socket": "end_a"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") + refused("attach onto a socket a closure holds", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Leg", "parent_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") + refused("attach onto the closing socket", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Brace", "parent_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") + refused("close of a part on itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Tie", "other_socket": "end_b"}, "'Tie' cannot close on itself") + refused("close of sockets that may not mate", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Hull", "other_socket": "lug_a_back"}, + "'Tie' closing on 'Hull': socket 'end_a' (pivot, size 0.054) and parent socket 'lug_a_back' (mount, size 0.09) are of different types") + refused("close of two sockets that are apart", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "m apart: place them so they meet") + refused("close on a mesh that is not a kit part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Plain", "other_socket": "a"}, "'Plain' is not a kit part") + refused("close of a socket the part does not have", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_c", "other_name": "Leg", "other_socket": "rod_end_back"}, + "part 'strut' has no socket 'end_c'") + was = np.array(brace.matrix_world) + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") + found = closure_row("Brace") + check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", + receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None + and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) + and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") + check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) + # closures-omitted: a second closure, named to sort first, far from the leg; then a receipt with room for one row. Mutant N5 (never + # omit) lists two rows; rows by name alone would keep Aa_Loose and drop the one this call opened. + anchor, loose = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]), place("Aa_Loose", "strut", "width=0.09") + meet = Matrix((np.array(anchor.matrix_world) @ core.mate(next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_b"), + next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_a"), 40.0)).tolist()) + send("setObjectTransform", targetObjectName="Aa_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + receipt, report = send("brokkr_kitbash.close", object_name="Aa_Loose", socket="end_a", other_name="Aa_Anchor", other_socket="end_b") + check("a loose part placed to meet a socket closes on it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") + ROWS = [{"part": "Brace", "to": "Leg", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] + check("set_params lists the closures its own part is an end of first, then the rest", receipt["status"] == "accepted" and report["closures"] == ROWS + and "closuresOmitted" not in report, report and report.get("closures")) + addon = sys.modules["brokkr_kitbash"] + limit = addon.REPORT_LIMIT + addon.REPORT_LIMIT = len(json.dumps({k: v for k, v in report.items() if k != "closures"}, separators=(",", ":"))) + 40 + len(json.dumps(ROWS[0], separators=(",", ":"))) + 1 + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") + addon.REPORT_LIMIT = limit + check("with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", receipt["status"] == "accepted" + and report["closures"] == ROWS[:1] and report.get("closuresOmitted") == 1 and np.array_equal(np.array(brace.matrix_world), was), report and [report.get("closures"), report.get("closuresOmitted")]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") + check("and a closure another part's set_params opened comes before one that holds", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}, {"part": "Brace", "to": "Leg", "holds": False}], report and report.get("closures")) + send("brokkr_kitbash.detach", object_name="Aa_Loose") + send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") + leg.scale = (1.0001, 1.0, 1.0) + bpy.context.view_layer.update() + found = closure_row("Brace") + leg.scale = (1.0, 1.0, 1.0) + bpy.context.view_layer.update() + check("a closure on a part scaled by hand reads broken, naming the part and why, not gone", found.get("to") == "Leg" and found.get("holds") is False and found.get("residual") is None + and "'Leg' is scaled, mirrored or sheared" in str(found.get("reason")) and closure_row("Brace").get("holds") is True, found) + twin = brace.copy() # as Shift-D leaves it: a second part stating the same closure + twin.data = brace.data.copy() + twin.name = "Brace_twin" + bpy.context.scene.collection.objects.link(twin) + found, other = closure_row("Brace"), closure_row("Brace_twin") + check("two parts that state a closure on one socket both read not held, each naming the other", found.get("holds") is False and other.get("holds") is False + and "is also closed on by 'Brace_twin'" in str(found.get("reason")) and "is also closed on by 'Brace'" in str(other.get("reason")), [found, other]) + tie["keeper"] = twin # something still points at the copy, so Delete leaves it in the file with its closure properties + with bpy.context.temp_override(selected_objects=[twin], active_object=twin): + bpy.ops.object.delete() + check("and with the copy deleted the closure holds again, though the copy is still in the file stating its own", closure_row("Brace").get("holds") is True + and bpy.data.objects.get("Brace_twin") is not None and "kit_close_to" in bpy.data.objects["Brace_twin"], closure_of("Brace")) + del tie["keeper"] + bpy.data.objects.remove(bpy.data.objects["Brace_twin"]) + refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") + refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.06) and parent socket 'rod_end' (pivot, size 0.054)") + receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") + check("set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"]["holds"] is False + and held(report) and 0.1 / math.sqrt(3) - 1e-5 <= report["closure"]["residual"] <= 0.1 + 1e-5, [receipt["message"], report and report["closure"]]) + send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") + before = np.array(brace.matrix_world) + receipt, report = send("brokkr_kitbash.detach", object_name="Brace") + check("detach clears the brace's closure with its connection, and it stays where it stood", receipt["status"] == "accepted" and report and report["closure"] is None + and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None + and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) + receipt, report = send("brokkr_kitbash.close", **CLOSING) + check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) + leg.name = "Shin" + found = closure_row("Brace") + check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) + leg.name = "Leg" + send("brokkr_kitbash.detach", object_name="Leg") + homes = list(leg.users_collection) + for home in homes: + home.objects.unlink(leg) + found = closure_row("Brace") + check("a closure on a part unlinked from every collection reads to null, holds false, with the reason", found.get("to", 0) is None and found.get("holds") is False + and "gone" in str(found.get("reason")) and "Leg" in bpy.data.objects, found) + for home in homes: + home.objects.link(leg) + check("and holds again once the part is linked back", closure_row("Brace").get("holds") is True, closure_of("Brace")) + with bpy.context.temp_override(selected_objects=[leg], active_object=leg): + bpy.ops.object.delete() # the ordinary Delete: the closure's pointer keeps the object in the file as an orphan + found = closure_row("Brace") + check("a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", found.get("to", 0) is None + and found.get("holds") is False and found.get("residual", 0) is None and bpy.data.objects.get("Leg") is not None and brace.get("kit_close_to") is not None, [found, list(bpy.data.objects.keys())]) + refused("close onto a deleted part that is still in the file", "brokkr_kitbash.close", + {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Leg' is in no collection") + if "Leg" in bpy.data.objects: + bpy.data.objects.remove(bpy.data.objects["Leg"]) + found = closure_row("Brace") + receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") + check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} + and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) + before = np.array(brace.matrix_world) + receipt, report = send("brokkr_kitbash.detach", object_name="Brace") + check("detach of a part that states only a closure clears it and leaves the part where it stood", receipt["status"] == "accepted" and report["closure"] is None + and not [k for k in brace.keys() if k.startswith("kit_close")] and np.array_equal(np.array(brace.matrix_world), before), [receipt["message"], dict(brace.items())]) + receipt, report = send("brokkr_kitbash.attach", object_name="Tie", socket="end_a", parent_name="Brace", parent_socket="end_b") + check("and the socket the closure held is free again", receipt["status"] == "accepted" and held(report), receipt["message"]) -# --- drift and detach --------------------------------------------------------------------------------------------------------- -send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) -found = connection("Nozzle") or {} -check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee" - and found["residual"] > 0.1, found) -refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach", - {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'") -send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") -check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, - connection("Nozzle")) -send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0]) -drifted = connection("Nozzle") or {} -send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3") -check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")]) -nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is -nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis -bpy.context.view_layer.update() -found = connection("Nozzle") or {} -check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5 - and seated(nozzle, "mount", tee, "c") < SEATED, found) -send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") -check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) -push = np.array(tee.matrix_world)[:3, :3].T @ [NUDGE, 0.0, 0.0] # NUDGE along the world's x, in the tee's frame -send("setObjectTransform", targetObjectName="Nozzle", location=(np.array(nozzle.matrix_basis)[:3, 3] + push).tolist()) -found = connection("Nozzle") or {} -check("a child moved by NUDGE does not hold, and its residual is the move", found.get("holds") is False - and abs(reading("nudged", found.get("residual") or 0.0) - NUDGE) < 0.1 * NUDGE, found) -send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") -check("and set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -for written in (float("nan"), "x"): # a kit_roll nobody's attach wrote - nozzle["kit_roll"] = written + # --- drift and detach --------------------------------------------------------------------------------------------------------- + send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) found = connection("Nozzle") or {} - check(f"a kit_roll of {written!r} reports roll null and does not hold", found.get("roll", 0.0) is None and found.get("holds") is False - and found.get("residual", 0.0) is None and found.get("parent") == "Tee", found) - refused(f"set_params on a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Nozzle", "params": "exit_r=0.3"}, - "'Nozzle' on 'Tee': its kit_roll is not a number: detach it and attach it again") - refused(f"set_params on the parent of a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "run=0.6"}, - "'Nozzle' on 'Tee': its kit_roll is not a number") -receipt, report = send("brokkr_kitbash.detach", object_name="Nozzle") -check("detach clears a roll that is not a number", receipt["status"] == "accepted" and nozzle.parent is None and report and report["connection"] is None - and "kit_roll" not in nozzle, [receipt["message"], dict(nozzle.items())]) -receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) -check("and the nozzle attaches again", receipt["status"] == "accepted" and held(report) and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -send("setObjectParent", targetObjectName="Spare", parentObjectName="") -found = connection("Spare") -check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) -refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, - "'Spare' states a connection and has no parent") -send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain") -found = connection("Spare") or {} -refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, - "'Plain' is not a kit part") -receipt, report = send("brokkr_kitbash.detach", object_name="Spare") -check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None - and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report]) + check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee" + and found["residual"] > 0.1, found) + refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach", + {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'") + send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") + check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, + connection("Nozzle")) + send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0]) + drifted = connection("Nozzle") or {} + send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3") + check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")]) + nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is + nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis + bpy.context.view_layer.update() + found = connection("Nozzle") or {} + check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5 + and seated(nozzle, "mount", tee, "c") < SEATED, found) + send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") + check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) + push = np.array(tee.matrix_world)[:3, :3].T @ [NUDGE, 0.0, 0.0] # NUDGE along the world's x, in the tee's frame + send("setObjectTransform", targetObjectName="Nozzle", location=(np.array(nozzle.matrix_basis)[:3, 3] + push).tolist()) + found = connection("Nozzle") or {} + check("a child moved by NUDGE does not hold, and its residual is the move", found.get("holds") is False + and abs(reading("nudged", found.get("residual") or 0.0) - NUDGE) < 0.1 * NUDGE, found) + send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") + check("and set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + for written in (float("nan"), "x"): # a kit_roll nobody's attach wrote + nozzle["kit_roll"] = written + found = connection("Nozzle") or {} + check(f"a kit_roll of {written!r} reports roll null and does not hold", found.get("roll", 0.0) is None and found.get("holds") is False + and found.get("residual", 0.0) is None and found.get("parent") == "Tee", found) + refused(f"set_params on a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Nozzle", "params": "exit_r=0.3"}, + "'Nozzle' on 'Tee': its kit_roll is not a number: detach it and attach it again") + refused(f"set_params on the parent of a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "run=0.6"}, + "'Nozzle' on 'Tee': its kit_roll is not a number") + receipt, report = send("brokkr_kitbash.detach", object_name="Nozzle") + check("detach clears a roll that is not a number", receipt["status"] == "accepted" and nozzle.parent is None and report and report["connection"] is None + and "kit_roll" not in nozzle, [receipt["message"], dict(nozzle.items())]) + receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) + check("and the nozzle attaches again", receipt["status"] == "accepted" and held(report) and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + send("setObjectParent", targetObjectName="Spare", parentObjectName="") + found = connection("Spare") + check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) + refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Spare' states a connection and has no parent") + send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain") + found = connection("Spare") or {} + refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Plain' is not a kit part") + receipt, report = send("brokkr_kitbash.detach", object_name="Spare") + check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None + and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report]) -before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")} -receipt, report = send("brokkr_kitbash.detach", object_name="Tee") -check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None - and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"] - and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]]) -check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0) -check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0] - and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee")) + before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")} + receipt, report = send("brokkr_kitbash.detach", object_name="Tee") + check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None + and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"] + and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]]) + check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0) + check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee")) -# --- boolean: the tank, with two material slots ----------------------------------------------------------------------------------- -send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) -send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) -tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) -STRAPS = 1 # the tank's second shape: the repeat of two straps -tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) -side = np.array(tank.matrix_world) @ [0.0, -0.22, 0.4564, 1.0] # under the barrel at the lower cradle: cradle, pad, strap and wall -send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) -box = bpy.data.objects["Box"] -box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) -raw = measure(tank.data) -receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") -modifier = tank.modifiers.get("Kit Difference") -check("boolean adds one Boolean modifier above the Bevel: Exact, self-intersection on, difference, over a collection that holds the cutter and is in no scene", - receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" - and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "COLLECTION", None) - and modifier.collection.objects[:] == [box] and modifier.collection.name == "Tank difference" - and not any(modifier.collection in c.children_recursive for c in [s.collection for s in bpy.data.scenes]), - [receipt["message"], [m.name for m in tank.modifiers]]) -shown, shown_slots = evaluated(tank) -check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown - and CUT < reading("cut", cut["evaluated"]["volume"]) < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 - and int(np.count_nonzero(tank_built.shape == STRAPS)) == 2 * 4 * 24 - and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], - [cut and cut["evaluated"], shown, raw]) -R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} -check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) -check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was - and "kit_part" not in box and bpy.context.scene.collection in box.users_collection, box_was) -refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, - "'Box' already cuts 'Tank' (its Kit Difference modifier's collection)") -refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") -refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") -send("createObject", objectType="EMPTY", name="Marker") -refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") -receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") -resized, _ = evaluated(tank) -check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" - and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and tank.modifiers["Kit Difference"].collection.objects[:] == [box] - and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] - and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) + # --- boolean: the tank, with two material slots ----------------------------------------------------------------------------------- + send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) + send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) + tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) + STRAPS = 1 # the tank's second shape: the repeat of two straps + tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) + side = np.array(tank.matrix_world) @ [0.0, -0.22, 0.4564, 1.0] # under the barrel at the lower cradle: cradle, pad, strap and wall + send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) + box = bpy.data.objects["Box"] + box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) + raw = measure(tank.data) + receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") + modifier = tank.modifiers.get("Kit Difference") + check("boolean adds one Boolean modifier above the Bevel: Exact, self-intersection on, difference, over a collection that holds the cutter and is in no scene", + receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" + and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "COLLECTION", None) + and modifier.collection.objects[:] == [box] and modifier.collection.name == "Tank difference" + and not any(modifier.collection in c.children_recursive for c in [s.collection for s in bpy.data.scenes]), + [receipt["message"], [m.name for m in tank.modifiers]]) + shown, shown_slots = evaluated(tank) + check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown + and CUT < reading("cut", cut["evaluated"]["volume"]) < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and int(np.count_nonzero(tank_built.shape == STRAPS)) == 2 * 4 * 24 + and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], + [cut and cut["evaluated"], shown, raw]) + R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} + check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) + check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was + and "kit_part" not in box and bpy.context.scene.collection in box.users_collection, box_was) + refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, + "'Box' already cuts 'Tank' (its Kit Difference modifier's collection)") + refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") + refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") + send("createObject", objectType="EMPTY", name="Marker") + refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") + receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") + resized, _ = evaluated(tank) + check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" + and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and tank.modifiers["Kit Difference"].collection.objects[:] == [box] + and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] + and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) -# --- apply ------------------------------------------------------------------------------------------------------------------------ -refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") -slots = [s.material and s.material.name for s in tank.material_slots] -shown, shown_slots = evaluated(tank) -index = np.zeros(len(tank.data.polygons), dtype=np.int32) -tank.data.polygons.foreach_get("material_index", index) -mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) -sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] -receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") -after = np.zeros(len(tank.data.polygons), dtype=np.int32) -tank.data.polygons.foreach_get("material_index", after) -check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", - receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) - and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] - and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) -check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] - and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots - and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) -check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" - and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) -refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") -refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") -receipt, report = send("brokkr_kitbash.report", object_name="Tank") -check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True - and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] - and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) -receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") -check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) + # --- apply ------------------------------------------------------------------------------------------------------------------------ + refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") + slots = [s.material and s.material.name for s in tank.material_slots] + shown, shown_slots = evaluated(tank) + index = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", index) + mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) + sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] + receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") + after = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", after) + check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", + receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) + and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] + and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) + check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] + and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots + and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) + check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" + and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) + refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") + refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") + receipt, report = send("brokkr_kitbash.report", object_name="Tank") + check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) + receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") + check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) -# --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- -plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) -send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) -send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) -receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") -receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") -check("two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", receipt["status"] == "accepted" - and [m.name for m in plate.modifiers] == ["Kit Difference", "Kit Bevel"] - and [o.name for o in plate.modifiers["Kit Difference"].collection.objects] == ["Slot", "Hole"] - and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] - and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 - and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), - [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) -R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} -twin = plate.copy() -twin.name = "Plate_twin" -bpy.context.scene.collection.objects.link(twin) -refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") -bpy.data.objects.remove(twin) -shown, shown_slots = evaluated(plate) -receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") -check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" - and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] - and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) -send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) -send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) -send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) -send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) -receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") -shown, shown_slots = evaluated(plate) -receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") -used = np.zeros(len(plate.data.polygons), dtype=np.int32) -plate.data.polygons.foreach_get("material_index", used) -check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", - receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True - and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] - and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] - and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) -vent = place("Vent", "vent", "width=0.2; height=0.15") -receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") -check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) -refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, - "'Vent' is below 'Plate'") -big = place("Big", "vent", "width=0.8; height=0.6") -refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, - "are mount sockets, where the child fits the parent: it is larger") + # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- + plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) + send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) + send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) + receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") + receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") + check("two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", receipt["status"] == "accepted" + and [m.name for m in plate.modifiers] == ["Kit Difference", "Kit Bevel"] + and [o.name for o in plate.modifiers["Kit Difference"].collection.objects] == ["Slot", "Hole"] + and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] + and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 + and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), + [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) + R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} + twin = plate.copy() + twin.name = "Plate_twin" + bpy.context.scene.collection.objects.link(twin) + refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") + bpy.data.objects.remove(twin) + shown, shown_slots = evaluated(plate) + receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") + check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" + and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] + and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) + send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) + send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) + send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) + receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") + shown, shown_slots = evaluated(plate) + receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") + used = np.zeros(len(plate.data.polygons), dtype=np.int32) + plate.data.polygons.foreach_get("material_index", used) + check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", + receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True + and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] + and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] + and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) + vent = place("Vent", "vent", "width=0.2; height=0.15") + receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") + check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) + refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, + "'Vent' is below 'Plate'") + big = place("Big", "vent", "width=0.8; height=0.6") + refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, + "are mount sockets, where the child fits the parent: it is larger") -# --- a tee is one solid under the Boolean ----------------------------------------------------------------------------------------- -place("Cross", "pipe_fitting", location=[0.0, -6.0, 0.0]) # pipe_r 0.05, the default -send("createObject", objectType="MESH", name="Bar", location=[0.0, -6.0, 0.0], size=1.0) -send("setObjectTransform", targetObjectName="Bar", scale=[0.3, 3.0, 0.3]) -receipt, cut = send("brokkr_kitbash.boolean", object_name="Cross", cutter="Bar") -R["tee"] = cut and cut["evaluated"] -check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut - and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) + # --- a tee is one solid under the Boolean ----------------------------------------------------------------------------------------- + place("Cross", "pipe_fitting", location=[0.0, -6.0, 0.0]) # pipe_r 0.05, the default + send("createObject", objectType="MESH", name="Bar", location=[0.0, -6.0, 0.0], size=1.0) + send("setObjectTransform", targetObjectName="Bar", scale=[0.3, 3.0, 0.3]) + receipt, cut = send("brokkr_kitbash.boolean", object_name="Cross", cutter="Bar") + R["tee"] = cut and cut["evaluated"] + check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut + and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) -# --- apply and empty material slots ----------------------------------------------------------------------------------------------- -keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) -send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) -keeper.data.materials.append(None) # an empty last slot the part was given -send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) -send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") -receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") -check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" - and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, - [receipt["message"], [m and m.name for m in keeper.data.materials]]) -gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) -send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) -send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) -gap = bpy.data.objects["Gap"] -gap.data.materials.append(None) # the cutter's faces are in an empty first slot -gap.data.materials.append(bpy.data.materials["Boss Brass"]) -gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot -send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") -receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") -used = np.zeros(len(gapped.data.polygons), dtype=np.int32) -gapped.data.polygons.foreach_get("material_index", used) -check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 - and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), - [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) -names = [m and m.name for m in gapped.data.materials] -brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] -far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach -check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", - names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) - and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) + # --- apply and empty material slots ----------------------------------------------------------------------------------------------- + keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) + send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + keeper.data.materials.append(None) # an empty last slot the part was given + send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) + send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") + receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") + check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" + and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, + [receipt["message"], [m and m.name for m in keeper.data.materials]]) + gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) + send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) + gap = bpy.data.objects["Gap"] + gap.data.materials.append(None) # the cutter's faces are in an empty first slot + gap.data.materials.append(bpy.data.materials["Boss Brass"]) + gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot + send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") + receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") + used = np.zeros(len(gapped.data.polygons), dtype=np.int32) + gapped.data.polygons.foreach_get("material_index", used) + check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 + and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), + [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) + names = [m and m.name for m in gapped.data.materials] + brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] + far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach + check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index de26a6f..cfce1ad 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -5,7 +5,9 @@ and each refusal changes nothing. Not part of the unittest run: it needs Blender blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_pose.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses -without them). is an absolute path; writes .result.json and exits 1 when a check failed. +without them). is an absolute path; writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. The scene: a tank, a bracket on its lug, a strut pinned in the bracket, an actuator pinned on the strut's far end, and a loose strut whose closure names the actuator's rod pin. Bounds follow lodur:ruling:deterministic-bound-margin: @@ -17,6 +19,7 @@ import json import math import os import sys +import traceback import tempfile import types from pathlib import Path @@ -168,143 +171,146 @@ def refused(label, action, fields, expected): [receipt["status"], receipt["message"]]) -rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows - and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows]) +try: + rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] + check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows + and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows]) -# --- the scene ---------------------------------------------------------------------------------------------------------- -tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09 -mount = place("Mount", "bracket") # pin 0.054, plate 0.09 -strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator") -spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket") -send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) -send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b") -send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a") -send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0) -receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0) -check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0) - and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")]) + # --- the scene ---------------------------------------------------------------------------------------------------------- + tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09 + mount = place("Mount", "bracket") # pin 0.054, plate 0.09 + strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator") + spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket") + send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) + send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b") + send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a") + send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0) + receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0) + check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0) + and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")]) -def meeting(name, other, other_socket, roll): - """Place a loose strut so its end_a meets a socket of another part, and close it there.""" - loose = place(name, "strut", "width=0.09") - meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist()) - send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) - return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket) + def meeting(name, other, other_socket, roll): + """Place a loose strut so its end_a meets a socket of another part, and close it there.""" + loose = place(name, "strut", "width=0.09") + meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist()) + send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket) -anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]) -receipt, report = meeting("Brace", ram, "rod_end", 50.0) -check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) -receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0) -check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) -brace = bpy.data.objects["Brace"] -closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} + anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]) + receipt, report = meeting("Brace", ram, "rod_end", 50.0) + check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0) + check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + brace = bpy.data.objects["Brace"] + closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} -# --- roll: in place ----------------------------------------------------------------------------------------------------- -for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at - was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) - sent = COUNT[0] - receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn) - gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"] - check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", - receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL - and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn), - [receipt["message"], report and report["connection"], gap, off]) - moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0)) - check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})", - (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL - and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]]) + # --- roll: in place ----------------------------------------------------------------------------------------------------- + for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at + was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) + sent = COUNT[0] + receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"] + check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", + receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL + and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn), + [receipt["message"], report and report["connection"], gap, off]) + moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0)) + check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})", + (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL + and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]]) -# --- roll: the closures it opens ---------------------------------------------------------------------------------------- -check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [ - {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures")) -receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0) -check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [ - {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures")) -send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0]) -receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0) -check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [ - {"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures")) -receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0) -check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [ - {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}] - and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())]) + # --- roll: the closures it opens ---------------------------------------------------------------------------------------- + check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures")) + receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0) + check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [ + {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures")) + send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0]) + receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0) + check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures")) + receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0) + check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}] + and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())]) -# --- aim ---------------------------------------------------------------------------------------------------------------- -for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))): - world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) - receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) - aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} - read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit) - grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180)) - apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0)) - check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", - receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid]) - gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"] - check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})", - aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) - and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, - [dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off]) + # --- aim ---------------------------------------------------------------------------------------------------------------- + for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))): + world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) + receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) + aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} + read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit) + grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180)) + apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0)) + check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", + receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid]) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"] + check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})", + aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) + and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off]) -# --- reach -------------------------------------------------------------------------------------------------------------- -for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)): - world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) - A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit) - current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one - send("brokkr_kitbash.roll", object_name="Strut", roll=current) - height = round(C + part * math.hypot(A, B), 3) - fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default - receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields) + # --- reach -------------------------------------------------------------------------------------------------------------- + for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)): + world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) + A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit) + current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one + send("brokkr_kitbash.roll", object_name="Strut", roll=current) + height = round(C + part * math.hypot(A, B), 3) + fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default + receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields) + reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} + apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731 + off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) + farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle + check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do", + receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER, + [receipt["message"], reached, off_plane, farther]) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"] + check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0 + and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL + and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], gap, off]) + + # --- refusals ----------------------------------------------------------------------------------------------------------- + send("setObjectParent", targetObjectName="Orphan", parentObjectName="") + low, high = C - math.hypot(A, B), C + math.hypot(A, B) + refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)") + refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached") + refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached") + refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it") + refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part") + refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, + "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin") + refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero") + refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach", + {"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}, + f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0")) + receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) + check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) + skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} + refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to") + receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew) reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} - apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731 - off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) - farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle - check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do", - receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER, - [receipt["message"], reached, off_plane, farther]) - gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"] - check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0 - and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL - and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, - [dict(strut.items()), report and report["connection"], gap, off]) - -# --- refusals ----------------------------------------------------------------------------------------------------------- -send("setObjectParent", targetObjectName="Orphan", parentObjectName="") -low, high = C - math.hypot(A, B), C + math.hypot(A, B) -refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)") -refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached") -refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached") -refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it") -refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part") -refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, - "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin") -refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero") -refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach", - {"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}, - f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0")) -receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) -check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) -skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} -refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to") -receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew) -reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} -over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high)) -check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted" - and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]), - [receipt["message"], reached, over, stands, high]) -refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0}, - "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin") -pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"] -for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))): - refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim", - {"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other") -refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0}, - "'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back") -refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") -refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll") -refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis") + over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high)) + check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted" + and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]), + [receipt["message"], reached, over, stands, high]) + refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0}, + "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin") + pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"] + for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))): + refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim", + {"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other") + refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0}, + "'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back") + refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") + refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll") + refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis") +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index e86c3ee..4845e67 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -6,12 +6,15 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. With BROKKR_POLISH_HULLS= it also repairs each and checks that no face was -turned. Writes .result.json and exits 1 when a check failed. +turned. Writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. """ import json import math import os import sys +import traceback import types from pathlib import Path @@ -98,331 +101,334 @@ def pixels_of(obj): return flat.reshape(image.size[1], image.size[0], 4)[..., :3], image -check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) +try: + check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) -# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward -# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ -size = 256 -rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north -baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) + # --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward + # --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ + size = 256 + rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north + baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) -def ball(bm): - bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) - layer = bm.loops.layers.uv.active - for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does - for loop in face.loops: - loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) - - -sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) -sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) -torn = bmesh.new() -torn.from_mesh(sphere.data) -bmesh.ops.split_edges(torn, edges=torn.edges[:]) -inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] -reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) -bmesh.ops.reverse_faces(torn, faces=inside_out) -torn.to_mesh(sphere.data) -torn.free() -sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) - - -def polygon_normals(mesh): - flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) - mesh.polygons.foreach_get("normal", flat) - return flat.reshape(-1, 3) - - -def shading_error(mesh): - """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" - flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) - mesh.corner_normals.foreach_get("vector", flat) - outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) - return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) - - -receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") -check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) -check("audit: welded topology sees one closed shell in the torn sphere", - before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) -check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 - and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps -check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", - reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles - and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) -torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) -receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") -check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) -check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) - and len(sphere.data.vertices) == 48 * 23 + 2, repaired) -check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) -normals_after = polygon_normals(sphere.data) -turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 -R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} -check("repair: by default turns no face (a single-sided material would cull a turned one)", - turned == 0 and repaired["changes"]["windingFlipped"] == 0 - and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) -check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 - and not repaired["changes"]["customNormalsDropped"], R["winding"]) - -# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- -receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) -after_pixels, after_image = pixels_of(sphere) -column = after_pixels[:, size // 2, 0] -north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 -ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) -ratio_after = float(column[north] / column[south]) -# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the -# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. -border = int(math.ceil(size * 0.1)) -deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) -R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} -check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" - and after_image.name == "ball_bake.delit" and after_image.packed_file is not None - and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) -check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) -# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half -# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 -check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) -# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 -check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) - -receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) -check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", - receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces - and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes - and rewound["after"]["windingAgainstNormals"] == 0, rewound) - -# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- -def holey(bm): - bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 - at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) - small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole - large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole - bmesh.ops.delete(bm, geom=small + large, context="FACES") - bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 - - -sheet = new_object("Sheet", holey) -flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess -flipped_sheet.from_mesh(sheet.data) -bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) -flipped_sheet.to_mesh(sheet.data) -flipped_sheet.free() -TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them -sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) -receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) -R["mend"] = mended -check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", - receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 - and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) -facing = polygon_normals(sheet.data)[:, 2] -check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) -shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) -sheet.data.corner_normals.foreach_get("vector", shading) -shading = shading.reshape(-1, 3) -fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] -old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] -check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", - len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), - [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) -bpy.data.objects.remove(sheet) - -# --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- -def pair(bm): - layer = bm.loops.layers.uv.active - for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other - made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) - for face in {f for v in made["verts"] for f in v.link_faces}: + def ball(bm): + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) + layer = bm.loops.layers.uv.active + for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does for loop in face.loops: - loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) + loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) -import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain - -twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) -twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) -twin = polish.arrays(twins) -twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) -owner, bary, _ = polish.core.rasterize(twin["UV"], size) -sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] -occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) -twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) -flat = np.ones((size, size, 4), dtype=np.float32) -flat[..., :3] = twin_bake -bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) -receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) -twin_after, _ = pixels_of(twins) -shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) -shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) -R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} -# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 -check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 - and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) -bpy.data.objects.remove(twins) - -# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- -slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) -slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) -sphere.location = (20, 0, 0) -bpy.context.view_layer.update() -receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) -corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) -extent = corners.max(axis=0) - corners.min(axis=0) -check("orient: long on Y, thin on Z, scaled to the length, centred", - receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) - and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) -check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) -check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] - and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) -receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") -check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) -bpy.data.objects.remove(slab) - -# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- -def knobbed(bm): - bmesh.ops.create_cube(bm, size=2.0) - top = next(f for f in bm.faces if f.normal.z > 0.9) - bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) - extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) - bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) - bmesh.ops.delete(bm, geom=[top], context="FACES") - bmesh.ops.triangulate(bm, faces=bm.faces[:]) - bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) + sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) + torn = bmesh.new() + torn.from_mesh(sphere.data) + bmesh.ops.split_edges(torn, edges=torn.edges[:]) + inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] + reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) + bmesh.ops.reverse_faces(torn, faces=inside_out) + torn.to_mesh(sphere.data) + torn.free() + sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) -block = new_object("Block", knobbed) -receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") -check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) -receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) -R["cut"] = cut -check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) - and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) -if receipt["status"] == "accepted": - knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] - part = {entry["name"]: entry for entry in cut["parts"]} - check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", - np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) - and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) - check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body - and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) - _, closed = send("brokkr_mesh_polish.audit") - check("cut_parts: both sides of the cut are capped (closed shells)", - all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), - {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) - capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} - check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 - and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) - cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons - if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} - check("cut_parts: each cap faces out of its own part, and no old face was turned", - all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) - and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) - check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] - and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) - # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot - receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) - pivot = knob.matrix_world.translation - reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) - R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} - # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y - check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body - and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 - and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) -receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") -check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + def polygon_normals(mesh): + flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) + mesh.polygons.foreach_get("normal", flat) + return flat.reshape(-1, 3) -# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- -def plate_body(bm): - bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 - bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) - bmesh.ops.triangulate(bm, faces=bm.faces[:]) + def shading_error(mesh): + """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) + return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) -def underside(name): - """Triangles of the part that face down and are surface, not cap.""" - part_object = bpy.data.objects[name] - return sum(1 for polygon in part_object.data.polygons - if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") + receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") + check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) + check("audit: welded topology sees one closed shell in the torn sphere", + before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) + check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 + and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps + check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles + and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) + torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) + receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") + check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) + check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) + and len(sphere.data.vertices) == 48 * 23 + 2, repaired) + check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) + normals_after = polygon_normals(sphere.data) + turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 + R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} + check("repair: by default turns no face (a single-sided material would cull a turned one)", + turned == 0 and repaired["changes"]["windingFlipped"] == 0 + and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) + check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 + and not repaired["changes"]["customNormalsDropped"], R["winding"]) + + # --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- + receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) + after_pixels, after_image = pixels_of(sphere) + column = after_pixels[:, size // 2, 0] + north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 + ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) + ratio_after = float(column[north] / column[south]) + # On the island's left border the gain field meets texels no triangle covers. With the field filled outward the + # border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. + border = int(math.ceil(size * 0.1)) + deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) + R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} + check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" + and after_image.name == "ball_bake.delit" and after_image.packed_file is not None + and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) + check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) + # bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half + # cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 + check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) + # bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 + check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) + + receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) + check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces + and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes + and rewound["after"]["windingAgainstNormals"] == 0, rewound) + + # --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- + def holey(bm): + bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 + at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) + small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole + large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole + bmesh.ops.delete(bm, geom=small + large, context="FACES") + bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 -R["through"] = {} -for label, through in (("without", 0.0), ("with", 0.1)): - new_object("Plate", plate_body) - # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, - # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once - receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) - R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None - for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: - bpy.data.objects.remove(leftover) -check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + sheet = new_object("Sheet", holey) + flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess + flipped_sheet.from_mesh(sheet.data) + bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) + flipped_sheet.to_mesh(sheet.data) + flipped_sheet.free() + TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them + sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) + receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) + R["mend"] = mended + check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 + and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) + facing = polygon_normals(sheet.data)[:, 2] + check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) + shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) + sheet.data.corner_normals.foreach_get("vector", shading) + shading = shading.reshape(-1, 3) + fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] + old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] + check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), + [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) + bpy.data.objects.remove(sheet) -# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- -panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) -panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) -for column_start in range(8, 120, 8): # yellow strokes over the whole texture - panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + # --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- + def pair(bm): + layer = bm.loops.layers.uv.active + for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other + made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) + for face in {f for v in made["verts"] for f in v.link_faces}: + for loop in face.loops: + loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) -def plate(bm): - bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain + + twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) + twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) + twin = polish.arrays(twins) + twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) + owner, bary, _ = polish.core.rasterize(twin["UV"], size) + sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] + occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) + twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) + flat = np.ones((size, size, 4), dtype=np.float32) + flat[..., :3] = twin_bake + bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) + receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) + twin_after, _ = pixels_of(twins) + shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) + shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) + R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} + # bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 + check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 + and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) + bpy.data.objects.remove(twins) + + # --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- + slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) + slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) + sphere.location = (20, 0, 0) + bpy.context.view_layer.update() + receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) + corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) + extent = corners.max(axis=0) - corners.min(axis=0) + check("orient: long on Y, thin on Z, scaled to the length, centred", + receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) + and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) + check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) + check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] + and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) + receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") + check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) + bpy.data.objects.remove(slab) + + # --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- + def knobbed(bm): + bmesh.ops.create_cube(bm, size=2.0) + top = next(f for f in bm.faces if f.normal.z > 0.9) + bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) + extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) + bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) + bmesh.ops.delete(bm, geom=[top], context="FACES") + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) -sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x -sign.location = (40, 0, 5) # clear of the block -bpy.context.view_layer.update() -camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) -bpy.context.scene.collection.objects.link(camera) -camera.data.type = "ORTHO" -camera.data.ortho_scale = 4.0 -camera.location = (40, 0, 9) -receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) -check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] - and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) -receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) -check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + block = new_object("Block", knobbed) + receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") + check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) + receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) + R["cut"] = cut + check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) + and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) + if receipt["status"] == "accepted": + knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] + part = {entry["name"]: entry for entry in cut["parts"]} + check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) + and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) + check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body + and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) + _, closed = send("brokkr_mesh_polish.audit") + check("cut_parts: both sides of the cut are capped (closed shells)", + all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), + {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) + capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} + check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 + and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) + cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons + if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} + check("cut_parts: each cap faces out of its own part, and no old face was turned", + all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) + and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) + check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] + and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) + # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot + receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) + pivot = knob.matrix_world.translation + reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) + R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} + # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y + check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body + and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 + and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") + check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) -def ink(pixels): - return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + # --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- + def plate_body(bm): + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 + bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) + bmesh.ops.triangulate(bm, faces=bm.faces[:]) -receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) -after, image = pixels_of(sign) -inside = np.zeros((128, 128), dtype=bool) -inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 -far = np.zeros((128, 128), dtype=bool) -far[:, 72:] = True # the other half of the sign -R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} -check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" - and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) -check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) -receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) -check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) -receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) -check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + def underside(name): + """Triangles of the part that face down and are surface, not cap.""" + part_object = bpy.data.objects[name] + return sum(1 for polygon in part_object.data.polygons + if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") -# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- -HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") -R["hulls"] = {} -for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: - known = set(bpy.data.objects.keys()) - bpy.ops.import_scene.gltf(filepath=str(path)) - for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: - was = polygon_normals(hull.data) - _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) - against = raw[hull.name]["windingAgainstNormals"] - receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) - now = polygon_normals(hull.data) - turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None - R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, - "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} - check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" - and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair - and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) - bpy.data.objects.remove(hull) + + R["through"] = {} + for label, through in (("without", 0.0), ("with", 0.1)): + new_object("Plate", plate_body) + # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, + # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) + R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None + for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: + bpy.data.objects.remove(leftover) + check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + + # --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- + panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) + for column_start in range(8, 120, 8): # yellow strokes over the whole texture + panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + + + def plate(bm): + bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + + + sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x + sign.location = (40, 0, 5) # clear of the block + bpy.context.view_layer.update() + camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) + bpy.context.scene.collection.objects.link(camera) + camera.data.type = "ORTHO" + camera.data.ortho_scale = 4.0 + camera.location = (40, 0, 9) + receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) + check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] + and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) + receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) + check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + + + def ink(pixels): + return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + + + receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) + after, image = pixels_of(sign) + inside = np.zeros((128, 128), dtype=bool) + inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 + far = np.zeros((128, 128), dtype=bool) + far[:, 72:] = True # the other half of the sign + R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} + check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" + and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) + check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) + receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) + check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) + receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) + check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + + # --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- + HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") + R["hulls"] = {} + for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: + known = set(bpy.data.objects.keys()) + bpy.ops.import_scene.gltf(filepath=str(path)) + for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: + was = polygon_normals(hull.data) + _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) + against = raw[hull.name]["windingAgainstNormals"] + receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) + now = polygon_normals(hull.data) + turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None + R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, + "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} + check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" + and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair + and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) + bpy.data.objects.remove(hull) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) for c in R["checks"]: diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index ead0f7d..0bc76a1 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -125,7 +125,7 @@ "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", - "observedAt": "2026-12-02T11:45:23.730020+00:00" + "observedAt": "2026-12-02T12:26:00.225314+00:00" } }, { @@ -231,21 +231,21 @@ "Ball" ], "explainedByLight": { - "before": 0.971864311889026, - "after": 0.0005166699920249318 + "before": 0.9718639234640993, + "after": 0.0005166608648451421 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166056941702677, + "upDownLuminanceRatio": 1.016606182115671, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857550779013501, - "median": 1.4570952973825366, - "max": 3.0649084607569628, + "min": 0.9857558916878914, + "median": 1.4570992824185989, + "max": 3.0649098409031676, "clamped": 0.0 } } @@ -374,21 +374,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085379, - "after": 0.028075104345557378 + "before": 0.9999597575085377, + "after": 0.02807510434956728 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767501422, - "occlusionCorrelation": 0.4047107903549991 + "upDownLuminanceRatio": 0.9999964767498971, + "occlusionCorrelation": 0.4047107903548106 }, "gain": { - "min": 0.9999809983874741, - "median": 1.0000990920454487, - "max": 5.493916964791895, + "min": 0.9999809983877584, + "median": 1.0000990920471027, + "max": 5.493916964801517, "clamped": 0.0 } }, @@ -572,15 +572,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748391154895e-08, + "X": 1.8120748396474917e-08, "Y": 0.1508370330678463, - "Z": 1.836306858436306e-08 + "Z": 1.836306858237196e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218169195449718e-09 + -1.8218171415895767e-09 ], "knobReach": 3.0, "parent": "Block.body" @@ -678,21 +678,21 @@ "Ball" ], "explainedByLight": { - "before": 0.971864311889026, - "after": 0.0005166699920249318 + "before": 0.9718639234640993, + "after": 0.0005166608648451421 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166056941702677, + "upDownLuminanceRatio": 1.016606182115671, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857550779013501, - "median": 1.4570952973825366, - "max": 3.0649084607569628, + "min": 0.9857558916878914, + "median": 1.4570992824185989, + "max": 3.0649098409031676, "clamped": 0.0 } }, @@ -738,21 +738,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085379, - "after": 0.028075104345557378 + "before": 0.9999597575085377, + "after": 0.02807510434956728 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767501422, - "occlusionCorrelation": 0.4047107903549991 + "upDownLuminanceRatio": 0.9999964767498971, + "occlusionCorrelation": 0.4047107903548106 }, "gain": { - "min": 0.9999809983874741, - "median": 1.0000990920454487, - "max": 5.493916964791895, + "min": 0.9999809983877584, + "median": 1.0000990920471027, + "max": 5.493916964801517, "clamped": 0.0 } }, @@ -814,15 +814,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748391154895e-08, + "X": 1.8120748396474917e-08, "Y": 0.1508370330678463, - "Z": 1.836306858436306e-08 + "Z": 1.836306858237196e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218169195449718e-09 + -1.8218171415895767e-09 ], "knobReach": 3.0, "parent": "Block.body" diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index a3c665c..8c85ac1 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -7,7 +7,9 @@ as a GLB the exporter hook has given VRMC_springBone. Not part of the unittest r Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Writes .result.json and .glb (the synthetic whale's rig, for the runtime's own parse, -Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The acceptance is the runtime's parse, not +Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. The acceptance is the runtime's parse, not anything here: the structure checks below are what this builder promised, not the runtime's rules. """ import json @@ -15,6 +17,7 @@ import math import os import struct import sys +import traceback import tempfile import time import types @@ -157,183 +160,186 @@ def world_of(nodes, parent, i): return out -whale = make_whale() -check("host file admitted", not R["hostErrors"] and {"brokkr_rig.body", "brokkr_rig.tendrils", "brokkr_rig.colliders"} <= set(R["hostRows"]), - R["hostErrors"] or R["hostRows"]) -whale.rotation_euler = (0.0, 0.0, math.radians(90)) # lying along x with a non-identity transform and an offset -whale.location = (0.4, -0.2, 0.1) -bpy.context.view_layer.update() -receipt, audit = send("brokkr_mesh_polish.audit", object_name="Whale") -R["audit"] = audit -check("fixture: one fused shell and a detached bead", audit and audit["Whale"]["shells"] == 2, audit) -receipt, _ = send("brokkr_mesh_polish.repair", object_name="Whale") -check("repair accepted", receipt["status"] == "accepted", receipt["message"]) -receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Whale", length=1.0) -check("orient accepted", receipt["status"] == "accepted", receipt["message"]) -receipt, body = send("brokkr_rig.body", object_name="Whale", spine_bones=6, head="+y", seeds="jaw=0,0.45,0.05", smooth_rounds=2) -check("body accepted", receipt["status"] == "accepted", receipt["message"]) -R["body"] = body -if body: - arm = bpy.data.objects[body["armature"]] - check("body: a spine of six, a jaw bone parented to a spine bone", body["spine"] == [f"spine_{i:02d}" for i in range(6)] - and [p["name"] for p in body["parts"]] == ["jaw"] and body["parts"][0]["triangles"] > 0 - and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) - head, tail = np.array(body["head"]), np.array(body["tail"]) - check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] - and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) -receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) -R["tendrils"] = tendrils -if tendrils: - check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", - tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) -receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) -R["colliders"] = colliders +try: + whale = make_whale() + check("host file admitted", not R["hostErrors"] and {"brokkr_rig.body", "brokkr_rig.tendrils", "brokkr_rig.colliders"} <= set(R["hostRows"]), + R["hostErrors"] or R["hostRows"]) + whale.rotation_euler = (0.0, 0.0, math.radians(90)) # lying along x with a non-identity transform and an offset + whale.location = (0.4, -0.2, 0.1) + bpy.context.view_layer.update() + receipt, audit = send("brokkr_mesh_polish.audit", object_name="Whale") + R["audit"] = audit + check("fixture: one fused shell and a detached bead", audit and audit["Whale"]["shells"] == 2, audit) + receipt, _ = send("brokkr_mesh_polish.repair", object_name="Whale") + check("repair accepted", receipt["status"] == "accepted", receipt["message"]) + receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Whale", length=1.0) + check("orient accepted", receipt["status"] == "accepted", receipt["message"]) + receipt, body = send("brokkr_rig.body", object_name="Whale", spine_bones=6, head="+y", seeds="jaw=0,0.45,0.05", smooth_rounds=2) + check("body accepted", receipt["status"] == "accepted", receipt["message"]) + R["body"] = body + if body: + arm = bpy.data.objects[body["armature"]] + check("body: a spine of six, a jaw bone parented to a spine bone", body["spine"] == [f"spine_{i:02d}" for i in range(6)] + and [p["name"] for p in body["parts"]] == ["jaw"] and body["parts"][0]["triangles"] > 0 + and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) + head, tail = np.array(body["head"]), np.array(body["tail"]) + check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] + and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) + receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) + check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) + R["tendrils"] = tendrils + if tendrils: + check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) + receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") + check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) + R["colliders"] = colliders -def skin_state(): - """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" - groups = [g.name for g in whale.vertex_groups] - weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] - props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] - for b in arm.data.bones if "rig_chain" in b} - return weights, props + def skin_state(): + """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" + groups = [g.name for g in whale.vertex_groups] + weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] + props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] + for b in arm.data.bones if "rig_chain" in b} + return weights, props -first = skin_state() -send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) -other = skin_state() -receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils with other knobs changes the skin", other != first, None) -check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) -check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) - and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge -receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 - and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) - and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) -R["colliders"] = colliders + first = skin_state() + send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) + other = skin_state() + receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) + check("tendrils with other knobs changes the skin", other != first, None) + check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) + check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) + and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge + receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") + check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 + and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) + and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) + R["colliders"] = colliders -# --- export: the five attributes, weights, extension, structure ---------------------------------------------------- -receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) -check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) -gltf, blob, bin_at = glb_json(WORK / "whale.glb") -ext = gltf.get("extensions", {}).get("VRMC_springBone") -check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) -if ext and tendrils and colliders: - check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] - and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] - and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] - and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], - [len(ext["springs"]), len(ext["colliders"])]) -check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) -if ext: - check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", - all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 - and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), - [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) -prims = [p for m in gltf["meshes"] for p in m["primitives"]] -check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), - [sorted(p["attributes"]) for p in prims]) -worst_sum, worst_count = 0.0, 0 -for p in prims: - if "WEIGHTS_0" not in p["attributes"]: - check("every primitive is skinned", False, sorted(p["attributes"])) - continue - acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] - view = gltf["bufferViews"][acc["bufferView"]] - W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) - worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) - worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) -check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) -nodes = gltf["nodes"] -parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} -check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) -joints = gltf["skins"][0]["joints"] -check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) -if ext: - in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} - linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) - for s in ext["springs"]) - check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear - and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) - check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) - check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) - swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) - where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] - expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] - check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) -R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} -Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) + # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- + receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) + check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) + gltf, blob, bin_at = glb_json(WORK / "whale.glb") + ext = gltf.get("extensions", {}).get("VRMC_springBone") + check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) + if ext and tendrils and colliders: + check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] + and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] + and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] + and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], + [len(ext["springs"]), len(ext["colliders"])]) + check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) + if ext: + check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 + and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), + [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) + prims = [p for m in gltf["meshes"] for p in m["primitives"]] + check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), + [sorted(p["attributes"]) for p in prims]) + worst_sum, worst_count = 0.0, 0 + for p in prims: + if "WEIGHTS_0" not in p["attributes"]: + check("every primitive is skinned", False, sorted(p["attributes"])) + continue + acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] + view = gltf["bufferViews"][acc["bufferView"]] + W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) + worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) + worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) + check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) + nodes = gltf["nodes"] + parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} + check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) + joints = gltf["skins"][0]["joints"] + check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) + if ext: + in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} + linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) + for s in ext["springs"]) + check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear + and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) + check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) + check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) + where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] + expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] + check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) + R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} + Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) -# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ -send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) -a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] -check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) -send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) -flat, _, _ = glb_json(WORK / "flat.glb") -fext = flat.get("extensions", {}).get("VRMC_springBone") -if ext and fext: - nodes_f = flat["nodes"] - parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} - names = {n["name"]: i for i, n in enumerate(nodes)} + # --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ + send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) + a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] + check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) + send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) + flat, _, _ = glb_json(WORK / "flat.glb") + fext = flat.get("extensions", {}).get("VRMC_springBone") + if ext and fext: + nodes_f = flat["nodes"] + parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} + names = {n["name"]: i for i, n in enumerate(nodes)} - def collider_world(gl, nd, par, c, key): - return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] + def collider_world(gl, nd, par, c, key): + return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] - pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) - for c, f in zip(ext["colliders"], fext["colliders"])] - check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", - bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) -bpy.ops.mesh.primitive_cube_add() -cube = bpy.context.active_object -cube.name = "Cube" -send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) -cube_json, _, _ = glb_json(WORK / "cube.glb") -check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) - and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) + pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) + for c, f in zip(ext["colliders"], fext["colliders"])] + check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) + bpy.ops.mesh.primitive_cube_add() + cube = bpy.context.active_object + cube.name = "Cube" + send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) + cube_json, _, _ = glb_json(WORK / "cube.glb") + check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) + and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) -# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs -chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) -receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") -check("body again clears the chain bones it would orphan", - rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) -check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) -send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) -cleared_json, _, _ = glb_json(WORK / "cleared.glb") -check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) -receipt, lone = send("brokkr_rig.colliders", object_name="Whale") -send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) -only_json, _, _ = glb_json(WORK / "colliders_only.glb") -check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) - and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) -receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] - and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) + # --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs + chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) + receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") + check("body again clears the chain bones it would orphan", + rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) + check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) + send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) + cleared_json, _, _ = glb_json(WORK / "cleared.glb") + check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) + receipt, lone = send("brokkr_rig.colliders", object_name="Whale") + send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) + only_json, _, _ = glb_json(WORK / "colliders_only.glb") + check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) + and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) + receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) + check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] + and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) -# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- -ball = bmesh.new() -bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) -ball_mesh = bpy.data.meshes.new("Ball") -ball.to_mesh(ball_mesh) -ball.free() -ball_obj = bpy.data.objects.new("Ball", ball_mesh) -bpy.context.scene.collection.objects.link(ball_obj) -send("brokkr_rig.body", object_name="Ball", spine_bones=4) + # --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- + ball = bmesh.new() + bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) + ball_mesh = bpy.data.meshes.new("Ball") + ball.to_mesh(ball_mesh) + ball.free() + ball_obj = bpy.data.objects.new("Ball", ball_mesh) + bpy.context.scene.collection.objects.link(ball_obj) + send("brokkr_rig.body", object_name="Ball", spine_bones=4) -def ball_weights(): - names = [g.name for g in ball_obj.vertex_groups] - return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] + def ball_weights(): + names = [g.name for g in ball_obj.vertex_groups] + return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] -before = ball_weights() -receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) -check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 - and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) -check("and leaves the skin as body made it, with no chain bones", ball_weights() == before - and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) + before = ball_weights() + receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) + check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 + and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) + check("and leaves the skin as body made it, with no chain bones", ball_weights() == before + and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 91255bf..e54abae 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-s67r7hee\\whale.glb (301168 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-qccur36g\\whale.glb (301168 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", From 617eb2acbcd36433b84f96135751fb20cde6d1d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 13:29:46 +0100 Subject: [PATCH 10/10] brokkr_kitbash.shell: count_folds counts the folded faces of the evaluated wall; the cage estimate is gone The fold receipt read from the cage ({onset, margin, edge, weight}) was no bound in either direction: seeded lofts fold at 0.03 to 0.44 of it, and it warned on Seraph plates that do not fold. core.fold_depths and the receipt are deleted. With count_folds, shell evaluates the wall alone (Kit Subsurf and Kit Solidify, every other modifier hidden for the reading and shown again) and reports folded: inner faces with a corner turned to run with their outer twin's normal. Without it folded is null and nothing is evaluated. Measured: 3.9 ms on a new plate of 1600 subdivided faces; nothing separable on a rebuild under six cutters (0.94 s against 0.92 s). Live kitbash_faceted holds the count to its own, face for face, on the wedge, on three of Soul's seeded lofts (seed 5185 offset -1, 5101 offset 0, 5196 offset 1; tests/fixtures/fold_lofts.json) and on a rebuild under cutters. Mutants caught there: never folded, all corners for any, stack left hidden. docs/kitbash.md: folded 0 is not yet a wall an Exact Boolean takes cleanly; on the Seraph's cap and breast it left open edges from 0.91 of the first folding thickness, on one hand of a mirrored pair. Finding: aetheria-release:finding:cut-kit-faceted-shell.s3.fold-receipt-margin-is-not-a-bound Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 53 +- .../brokkr_kitbash/brokkr_actions.json | 8 +- surfaces/blender/brokkr_kitbash/core.py | 37 -- surfaces/blender/docs/kitbash.md | 41 +- .../blender/tests/fixtures/fold_lofts.json | 543 ++++++++++++++++++ .../blender/tests/live/kitbash_faceted.py | 76 ++- .../tests/live/kitbash_faceted.result.json | 50 +- surfaces/blender/tests/test_kitbash.py | 54 +- 8 files changed, 735 insertions(+), 127 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/fold_lofts.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index c557c76..076453a 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -57,6 +57,7 @@ solves a loop: a closure never places a part, and a report says how far its two bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} +import contextlib import json import math @@ -1304,6 +1305,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward") levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels") bevel: bpy.props.FloatProperty(name="Bevel", default=0.0, min=0.0, max=0.1, description="Width of the Kit Bevel on the plate's edges; 0: none") + count_folds: bpy.props.BoolProperty(name="Count Folds", default=False, description="Evaluate the wall and report how many of its inner faces fold") # the action table states thickness from 0.001: a float property rounds 0.001 up, so its bound stands just under @kit_work @@ -1316,6 +1318,13 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.") rigid(obj) own_mesh(obj, "rebuilding") + if self.count_folds: + unseen = [modifier.name for modifier in obj.modifiers if modifier.name in (SUBSURF, SOLIDIFY) and not modifier.show_viewport] + if unseen: + raise Refused(f"{obj.name!r} has its {' and '.join(unseen)} hidden in viewports, and count_folds reads the wall those two make. " + "Show them, or leave count_folds off; nothing changed.") + with self.wall_alone(obj): + evaluable(context, obj) try: document = json.loads(self.sheet) except ValueError as error: @@ -1355,20 +1364,46 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): corners = built.V[built.faces.reshape(-1, 4)] facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() - pairs, depths, ridges, weights = core.fold_depths(built, self.levels) - behind, front = 0.5 * (1.0 - self.offset), 0.5 * (1.0 + self.offset) # the wall's share behind the designed surface, and in front of it - with np.errstate(divide="ignore"): - onsets = depths / np.where(ridges, behind, front) # the thickness at which each cage edge's concave side holds its fold depth - first = int(onsets.argmin()) if len(onsets) and np.isfinite(onsets.min()) else None - fold = None if first is None else { - "onset": round(float(onsets[first]), 6), "margin": round(float(onsets[first]) / self.thickness, 4), - "edge": [[int(v) // built.points, int(v) % built.points] for v in pairs[first]], "weight": round(float(weights[first]), 6)} return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), - "fold": fold, + "folded": self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None, "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} + @staticmethod + @contextlib.contextmanager + def wall_alone(shell): + """The shell with every modifier but its Kit Subsurf and Kit Solidify hidden, and shown again on the way out: what + an evaluation inside reads is the wall, and no Boolean runs for it.""" + hidden = [modifier for modifier in shell.modifiers if modifier.name not in (SUBSURF, SOLIDIFY) and modifier.show_viewport] + for modifier in hidden: + modifier.show_viewport = False + try: + yield + finally: + for modifier in hidden: + modifier.show_viewport = True + + @staticmethod + def folded_faces(context, shell, faces: int) -> int: + """How many inner faces of a shell's wall fold, counted on the wall as Blender evaluates it (wall_alone): Kit + Solidify lists the `faces` subdivided faces of the designed surface, then their inner twins in the same order, + each wound the other way. An inner face folds when the turn at any of its corners runs with its outer twin's + normal instead of against it: the corner has passed over its neighbour. 0 is a wall that nowhere folds.""" + with BROKKR_KITBASH_OT_shell.wall_alone(shell): + _, evaluated = evaluable(context, shell) + mesh = evaluated.to_mesh() + try: + points, corners = np.zeros(3 * len(mesh.vertices)), np.zeros(len(mesh.loops), dtype=np.int32) + mesh.vertices.foreach_get("co", points) + mesh.loops.foreach_get("vertex_index", corners) + quads = points.reshape(-1, 3)[corners[:8 * faces].reshape(2, faces, 4)] + outward = np.cross(quads[0, :, 2] - quads[0, :, 0], quads[0, :, 3] - quads[0, :, 1]) + turns = np.cross(quads[1] - np.roll(quads[1], 1, axis=1), np.roll(quads[1], -1, axis=1) - quads[1]) + return int((np.einsum("fkc,fc->fk", turns, outward) > 0).any(axis=1).sum()) + finally: + evaluated.to_mesh_clear() + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index f286fd1..89ed135 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -719,7 +719,7 @@ }, { "name": "brokkr_kitbash.shell", - "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, fold ({onset, margin, edge, weight}: the thickness at which the cage says the wall first folds over itself beside an edge, onset over the thickness asked, the edge as two [ring, point] and its crease; null where no edge can fold; an estimate from the cage, margin under 1 is a folded wall), corners, subdividedFaces, facing, thickness, offset, levels and children.", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -771,6 +771,12 @@ "maximum": 0.1, "default": 0, "doc": "width of the Kit Bevel on the plate's edges; 0: none" + }, + { + "name": "count_folds", + "type": "boolean", + "default": false, + "doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over" } ] } diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index f932bd5..d6156c9 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1134,43 +1134,6 @@ def sheet(document: Any) -> Sheet: corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) -def fold_depths(built: Sheet, levels: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Where an even wall on a shell's cage would fold, from the cage alone: for every cage edge between two quads, - (pairs (E, 2) of vertex indices, depth (E,), ridge (E,), weight (E,)). depth is the wall depth on the edge's - concave side at which the wall's far face first folds over itself beside the edge when the edge is a full - crease between flat facets: (W / 2^levels) / tan(phi), W the lesser perpendicular reach of the two quads from - the edge (the narrower facet binds) and phi half the angle between their normals; infinite where they are - coplanar. ridge: the facets fall away from their normals, so the concave side is behind the surface (a wall - grown inward); else it is in front. weight is the edge's crease, 0 where it has none: under a full crease a - softer edge folds later than its depth, never sooner.""" - quads = built.faces.reshape(-1, 4) - V = built.V - normals = np.cross(V[quads[:, 2]] - V[quads[:, 0]], V[quads[:, 3]] - V[quads[:, 1]]) - normals /= np.linalg.norm(normals, axis=1)[:, None] - centres = V[quads].mean(axis=1) - sides = {} - for face, quad in enumerate(quads): - for k in range(4): - a, b = int(quad[k]), int(quad[(k + 1) % 4]) - sides.setdefault((min(a, b), max(a, b)), []).append((face, int(quad[(k + 2) % 4]), int(quad[(k + 3) % 4]))) - creased = {(int(a), int(b)): float(w) for (a, b), w in zip(built.creases, built.weights)} - pairs, depths, ridges, weights = [], [], [], [] - for (a, b), faces in sorted(sides.items()): - if len(faces) != 2: - continue - along = V[b] - V[a] - along /= np.linalg.norm(along) - reach = min(float(np.linalg.norm((V[v] - V[a]) - along * ((V[v] - V[a]) @ along))) for _, c, d in faces for v in (c, d)) - (f0, _, _), (f1, _, _) = faces - middle = 0.5 * (V[a] + V[b]) - phi = 0.5 * math.acos(float(np.clip(normals[f0] @ normals[f1], -1.0, 1.0))) - pairs.append((a, b)) - depths.append(reach / 2 ** levels / math.tan(phi) if phi > 1e-9 else math.inf) - ridges.append(bool(normals[f0] @ (centres[f1] - middle) + normals[f1] @ (centres[f0] - middle) < 0)) - weights.append(creased.get((a, b), 0.0)) - return np.array(pairs, dtype=np.int64).reshape(-1, 2), np.array(depths), np.array(ridges, dtype=bool), np.array(weights) - - # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 32fea95..1c7f452 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -351,9 +351,9 @@ The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, -`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `fold` (see Thickness at a crease), -`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`, all facts of the cage: it -reads no evaluated mesh. +`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `folded` (see Thickness at a crease), +`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. All but `folded` are facts +of the cage: without `count_folds`, `shell` reads no evaluated mesh. **Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is @@ -370,7 +370,7 @@ the outline, and the plate left between two bites is a tab. it; a rib deeper than the room a tight crease leaves is refused with the size to lower. **Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot -hold: it reads no evaluated mesh, and the limit is a fact of the subdivided one. Even thickness moves a vertex on a +hold: the limit is a fact of the subdivided mesh, not of the cage. Even thickness moves a vertex on a full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over @@ -384,16 +384,27 @@ uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself there, and a cut through that place is untested. -`shell` reports this at the call, from the cage: `fold` is `{onset, margin, edge, weight}`, or null where no cage -edge has a wall on its concave side. `onset` is the least `thickness` at which the figure above says some cage edge -folds, every edge between two quads taken as a full crease between flat facets, and the wall's share on that edge's -concave side taken from `offset`; `margin` is `onset` over the `thickness` asked, so under 1 the wall is expected to -fold; `edge` is that edge as two `[ring, point]` (points as built: 2C - 1 on a mirrored ring), and `weight` its -crease. It is an estimate: a `weight` under 1 folds later than `onset`, and where a crease runs out to the rim -through a tapering quad the wall can fold sooner. On the Seraph's fourteen creased plates the evaluated wall first -folded at 0.74 to 1.2 of `onset` in thirteen and at 2.6 of it in one, whose binding edge had a crease of 0.6 -(`experiments/mechs`, 2026-12-02). Keep `margin` over about 1.4 where a plate is cut near a crease, with a thinner -wall, fewer `levels` or wider facets, and count the turned inner faces of the evaluated wall when it matters. +No figure read from the cage bounds this. The flat-facet figure above, taken over every cage edge, is neither a +floor nor a ceiling on a real plate: on seeded lofts of planar trapezoid facets with partial crease runs the +evaluated wall first folded at 0.44 of it with the wall grown inward, at 0.03 of it at `offset` 0 and at 0.08 of it +grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (`tests/fixtures/fold_lofts.json` holds three of +those lofts; 2026-12-02). So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone, +`Kit Subsurf` and `Kit Solidify` with every other modifier hidden for the reading and shown again, and reports +`folded`, the number of the wall's inner faces that fold. An inner face folds when the turn at any of its corners +runs with its outer twin's normal: the corner has passed over its neighbour. That is sooner than the face's own +normal turning: on the Seraph's cap a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null +and nothing is evaluated. The count cost 3.9 ms on a new plate of 1600 subdivided faces (a call of 7.7 ms against +3.8 ms), and nothing measurable on a rebuild under six cutters (0.94 s against 0.92 s, the call's own Boolean), +medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). On a shell whose `Kit Subsurf` or +`Kit Solidify` is hidden in viewports `count_folds` is refused before anything is written. + +`folded` 0 is not yet a wall an Exact Boolean takes cleanly. Short of the fold the inner quads at a tight rim corner +are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and +leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face +folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as +well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `apply`, or a count on the evaluated +mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at +the corner. Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed @@ -598,7 +609,7 @@ vertices overflow. | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | -| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `fold` (`{onset, margin, edge, weight}`: the thickness at which the cage says the wall first folds beside an edge, or null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | +| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/fixtures/fold_lofts.json b/surfaces/blender/tests/fixtures/fold_lofts.json new file mode 100644 index 0000000..566c2b0 --- /dev/null +++ b/surfaces/blender/tests/fixtures/fold_lofts.json @@ -0,0 +1,543 @@ +{ + "about": "Lofts of planar trapezoid facets on which a shell's wall folds well under any figure read from the cage: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there. thickness is one at which the evaluated wall folds; holds, where the action's range reaches it, one at which it does not.", + "lofts": [ + { + "seed": 5185, + "levels": 1, + "offset": -1.0, + "thickness": 0.006342, + "holds": 0.001, + "sheet": { + "rings": [ + [ + [ + -0.824534, + 0.0, + -0.055726 + ], + [ + -0.20124, + 0.0, + -0.555671 + ], + [ + 0.277571, + 0.0, + -0.326276 + ], + [ + 0.355141, + 0.0, + -0.095203 + ], + [ + 0.451529, + 0.0, + -0.526972 + ], + [ + 0.730665, + 0.0, + -0.126214 + ] + ], + [ + [ + -0.644054, + 0.57461, + -0.007851 + ], + [ + -0.166195, + 0.57461, + -0.391143 + ], + [ + 0.200893, + 0.57461, + -0.215272 + ], + [ + 0.260364, + 0.57461, + -0.038117 + ], + [ + 0.334261, + 0.57461, + -0.36914 + ], + [ + 0.548265, + 0.57461, + -0.061892 + ] + ], + [ + [ + -0.670812, + 0.958364, + 0.100578 + ], + [ + -0.338388, + 0.958364, + -0.16606 + ], + [ + -0.083022, + 0.958364, + -0.043715 + ], + [ + -0.041652, + 0.958364, + 0.079523 + ], + [ + 0.009755, + 0.958364, + -0.150754 + ], + [ + 0.158628, + 0.958364, + 0.062984 + ] + ], + [ + [ + -0.121748, + 1.402066, + -0.069972 + ], + [ + 0.06524, + 1.402066, + -0.219956 + ], + [ + 0.208883, + 1.402066, + -0.151137 + ], + [ + 0.232154, + 1.402066, + -0.081816 + ], + [ + 0.261071, + 1.402066, + -0.211346 + ], + [ + 0.344812, + 1.402066, + -0.091119 + ] + ] + ], + "creases": [ + { + "ring": 1, + "from": 4, + "to": 5, + "weight": 0.3 + }, + { + "column": 3, + "from": 0, + "to": 3, + "weight": 1.0 + }, + { + "ring": 2, + "from": 0, + "to": 3, + "weight": 1.0 + } + ], + "rim": 0.5 + } + }, + { + "seed": 5101, + "levels": 3, + "offset": 0.0, + "thickness": 0.010394, + "holds": null, + "sheet": { + "rings": [ + [ + [ + -0.70481, + 0.0, + 0.07744 + ], + [ + -0.108308, + 0.0, + 0.00574 + ], + [ + 0.492256, + 0.0, + -0.339801 + ], + [ + 0.608357, + 0.0, + -0.456893 + ], + [ + 0.685935, + 0.0, + -0.379315 + ], + [ + 0.817607, + 0.0, + 0.061337 + ] + ], + [ + [ + -0.355146, + 0.797251, + 0.328588 + ], + [ + 0.181707, + 0.797251, + 0.264058 + ], + [ + 0.722214, + 0.797251, + -0.046929 + ], + [ + 0.826705, + 0.797251, + -0.152312 + ], + [ + 0.896525, + 0.797251, + -0.082492 + ], + [ + 1.01503, + 0.797251, + 0.314095 + ] + ], + [ + [ + -0.785461, + 1.527843, + -0.183277 + ], + [ + -0.308259, + 1.527843, + -0.240637 + ], + [ + 0.172192, + 1.527843, + -0.51707 + ], + [ + 0.265072, + 1.527843, + -0.610743 + ], + [ + 0.327135, + 1.527843, + -0.548681 + ], + [ + 0.432473, + 1.527843, + -0.19616 + ] + ], + [ + [ + -0.488084, + 2.123542, + -0.236617 + ], + [ + -0.070532, + 2.123542, + -0.286807 + ], + [ + 0.349863, + 2.123542, + -0.528686 + ], + [ + 0.431133, + 2.123542, + -0.61065 + ], + [ + 0.485438, + 2.123542, + -0.556346 + ], + [ + 0.577608, + 2.123542, + -0.247889 + ] + ], + [ + [ + -0.714517, + 2.852512, + 0.062817 + ], + [ + -0.356616, + 2.852512, + 0.019796 + ], + [ + 0.003723, + 2.852512, + -0.187528 + ], + [ + 0.073383, + 2.852512, + -0.257783 + ], + [ + 0.11993, + 2.852512, + -0.211237 + ], + [ + 0.198933, + 2.852512, + 0.053154 + ] + ] + ], + "creases": [ + { + "ring": 2, + "from": 3, + "to": 5, + "weight": 1.0 + }, + { + "column": 1, + "from": 3, + "to": 4, + "weight": 0.6 + }, + { + "column": 3, + "from": 3, + "to": 4, + "weight": 1.0 + } + ], + "rim": 0.0 + } + }, + { + "seed": 5196, + "levels": 1, + "offset": 1.0, + "thickness": 0.00617, + "holds": null, + "sheet": { + "rings": [ + [ + [ + -0.383345, + 0.0, + -0.359947 + ], + [ + -0.036452, + 0.0, + -0.050835 + ], + [ + 0.567786, + 0.0, + -0.587238 + ], + [ + 0.622834, + 0.0, + -0.467053 + ], + [ + 0.672276, + 0.0, + -0.379683 + ], + [ + 0.730008, + 0.0, + -0.43819 + ] + ], + [ + [ + -0.557286, + 0.459757, + -0.324159 + ], + [ + -0.2711, + 0.459757, + -0.069142 + ], + [ + 0.227397, + 0.459757, + -0.511675 + ], + [ + 0.272811, + 0.459757, + -0.412522 + ], + [ + 0.313601, + 0.459757, + -0.340441 + ], + [ + 0.36123, + 0.459757, + -0.38871 + ] + ], + [ + [ + -0.062837, + 0.80579, + -0.458467 + ], + [ + 0.162644, + 0.80579, + -0.257545 + ], + [ + 0.555399, + 0.80579, + -0.606206 + ], + [ + 0.591179, + 0.80579, + -0.528086 + ], + [ + 0.623317, + 0.80579, + -0.471295 + ], + [ + 0.660843, + 0.80579, + -0.509325 + ] + ], + [ + [ + -0.125811, + 1.151684, + -0.10837 + ], + [ + 0.038964, + 1.151684, + 0.038458 + ], + [ + 0.325977, + 1.151684, + -0.216334 + ], + [ + 0.352124, + 1.151684, + -0.159246 + ], + [ + 0.375609, + 1.151684, + -0.117745 + ], + [ + 0.403032, + 1.151684, + -0.145536 + ] + ], + [ + [ + 0.161946, + 1.542628, + 0.17642 + ], + [ + 0.266014, + 1.542628, + 0.269154 + ], + [ + 0.447285, + 1.542628, + 0.108233 + ], + [ + 0.463799, + 1.542628, + 0.144288 + ], + [ + 0.478632, + 1.542628, + 0.170499 + ], + [ + 0.495952, + 1.542628, + 0.152947 + ] + ] + ], + "creases": [ + { + "ring": 3, + "from": 3, + "to": 4, + "weight": 1.0 + }, + { + "column": 3, + "from": 3, + "to": 4, + "weight": 1.0 + } + ], + "rim": 0.5 + } + } + ] +} diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index 4d04ed4..ec02c59 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -30,6 +30,7 @@ import bpy import numpy as np from mathutils import Matrix, Vector from mathutils.bvhtree import BVHTree +from mathutils.geometry import normal as triangle_normal SURFACE = Path(__file__).resolve().parents[2] sys.path.insert(0, str(SURFACE / "tools")) @@ -84,10 +85,10 @@ SOLID = 0.0313 # Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped # 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. EVEN = 1.5e-3 -# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet. The -# wall is built at FOLD / FOLD_STEP (no inner face turned) and at FOLD x FOLD_STEP (some turned). Least claimed mutant: -# F1, the wider facet's reach taken (max for min in core.fold_depths), which reads 0.25, 3.3 of shipped; FOLD_STEP is -# the 1.2 separation the margin rule asks on each side of the onset. +# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet, as +# measured on flat facets (docs/kitbash.md, Thickness at a crease). The wall is built at FOLD / FOLD_STEP (no inner +# face folded) and at FOLD x FOLD_STEP (some folded); FOLD_STEP is the 1.2 separation the margin rule asks on each +# side of the onset. The counts themselves are exact: count_folds is held to this script's own count, face for face. FOLD, FOLD_STEP = 0.075, 1.2 @@ -213,7 +214,7 @@ try: and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", - report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "fold", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) @@ -252,34 +253,47 @@ try: surface.free() check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"]) - # --- shell-fold: the receipt's fold onset, against the evaluated wall --------------------------------------------------------- + # --- shell-fold: count_folds, against this script's own count on the evaluated wall ------------------------------------------- section("shell-fold") # a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075 wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)], "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]} - def folded(name, thickness, offset=-1.0): - """(the receipt's fold, inner faces of the evaluated wall whose normal runs with their outer face's).""" - _, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(wedge), thickness=thickness, offset=offset, levels=2) - wall_mesh = evaluated(bpy.data.objects[name]) + def own_folds(obj): + """This script's count on its own evaluation: inner faces of the wall (Subsurf and Solidify alone) with a corner + whose triangle, the corner and its two neighbours, faces with their outer twin's normal (mathutils' normals).""" + wall_mesh = evaluated(obj, off=("BOOLEAN", "BEVEL")) wall_mesh.faces.ensure_lookup_table() - count = len(bpy.data.objects[name].data.polygons) * 4 ** 2 # Solidify lists the outer faces, then their inner twins in the same order, then the rim - turned = sum(1 for k in range(count) if wall_mesh.faces[k].normal.dot(wall_mesh.faces[count + k].normal) > 0) + count = len(obj.data.polygons) * 4 ** obj.modifiers["Kit Subsurf"].levels # Solidify lists the outer faces, then their inner twins in the same order, then the rim + found = 0 + for k in range(count): + at = [v.co for v in wall_mesh.faces[count + k].verts] + found += any(triangle_normal(at[i - 1], at[i], at[(i + 1) % len(at)]).dot(wall_mesh.faces[k].normal) > 0 for i in range(len(at))) wall_mesh.free() - return told["fold"], turned + return found - under, over = folded("FoldUnder", FOLD / FOLD_STEP), folded("FoldOver", FOLD * FOLD_STEP) + def folded(name, sheet, thickness, offset=-1.0, levels=2, **asked): + """[the report's folded (-1: no report), this script's own count].""" + _, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=offset, levels=levels, **asked) + return [told.get("folded", -1) if told else -1, own_folds(bpy.data.objects[name]) if name in bpy.data.objects else -1] + + under, over = folded("FoldUnder", wedge, FOLD / FOLD_STEP, count_folds=True), folded("FoldOver", wedge, FOLD * FOLD_STEP, count_folds=True) reading("foldUnder", under[1]) reading("foldOver", over[1], least=True) - check("shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", - abs(under[0]["onset"] - FOLD) < 1e-6 and abs(under[0]["margin"] - FOLD_STEP) < 1e-3 and abs(over[0]["margin"] - 1 / FOLD_STEP) < 1e-3 - and under[0]["edge"] in ([[0, 1], [1, 1]], [[1, 1], [2, 1]]) and under[0]["weight"] == 1.0 and under[1] == 0 and over[1] > 0, [under, over]) - outward = folded("FoldOut", 0.3, offset=1.0) - half = folded("FoldHalf", FOLD / FOLD_STEP, offset=0.0) - check("shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", - outward == (None, 0) and abs(half[0]["onset"] - 2 * FOLD) < 1e-6 and half[1] == 0, [outward, half]) - for name in ("FoldUnder", "FoldOver", "FoldOut", "FoldHalf"): - bpy.data.objects.remove(bpy.data.objects[name]) + check("shell-fold: count_folds counts no folded face on a creased ridge under the thickness its narrower facet holds, and the faces this script counts over it", + under == [0, 0] and over[0] == over[1] > 0, [under, over]) + unasked, outward = folded("FoldUnasked", wedge, FOLD * FOLD_STEP), folded("FoldOut", wedge, 0.3, offset=1.0, count_folds=True) + check("shell-fold: folded is null unless count_folds asks, whatever the wall does, and a ridge under a wall grown outward folds nowhere", + unasked[0] is None and unasked[1] == over[1] and outward == [0, 0], [unasked, outward]) + lofts = json.loads((SURFACE / "tests" / "fixtures" / "fold_lofts.json").read_text(encoding="utf-8"))["lofts"] + seeded = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Loft{loft['seed']}", loft["sheet"], loft["thickness"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts} + held = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Held{loft['seed']}", loft["sheet"], loft["holds"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts if loft["holds"]} + R["folds"] = {"seeded": seeded, "held": held} + check("shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds", + len(seeded) == 3 and all(told == own > 0 for told, own in seeded.values()) and held and all(pair == [0, 0] for pair in held.values()), [seeded, held]) + for name in ["FoldUnder", "FoldOver", "FoldUnasked", "FoldOut"] + [f"{kind}{loft['seed']}" for loft in lofts for kind in ("Loft", "Held")]: + if name in bpy.data.objects: + bpy.data.objects.remove(bpy.data.objects[name]) # --- shell-solid ------------------------------------------------------------------------------------------------------------ section("shell-solid") @@ -356,15 +370,22 @@ try: plate = evaluated(again) check("shell-rebuild: the rebuilt plate is still cut, and closed", sum(1 for e in plate.edges if not e.is_manifold) == 0 and len(plate.faces) > 2 * 400 + 4 * 20 + 20, len(plate.faces)) plate.free() + receipt, report = send("brokkr_kitbash.shell", object_name="Pauldron", sheet=json.dumps(MOVED), thickness=0.05, levels=2, bevel=0.004, count_folds=True) + check("shell-rebuild: count_folds under cutters counts the wall as this script does and leaves the stack shown, in order", + receipt["status"] == "accepted" and report and report["folded"] == own_folds(again) and [(m.name, m.show_viewport) for m in again.modifiers] + == [("Kit Subsurf", True), ("Kit Solidify", True), ("Kit Difference", True), ("Kit Bevel", True)], [receipt["message"], report and report.get("folded"), [(m.name, m.show_viewport) for m in again.modifiers]]) # --- costs: wall times of this run, never bounded ----------------------------------------------------------------------------- section("costs") - times = {"shell": [], "evaluation": [], "rebuildUnderCuts": []} + times = {"shell": [], "shellCountingFolds": [], "evaluation": [], "rebuildUnderCuts": [], "rebuildCall": [], "rebuildCallCountingFolds": []} for k in range(3): name = f"Timed{k}" start = time.perf_counter() bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(PAULDRON), thickness=WALL) times["shell"].append(time.perf_counter() - start) + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name=name + "Counted", sheet=json.dumps(PAULDRON), thickness=WALL, count_folds=True) + times["shellCountingFolds"].append(time.perf_counter() - start) bpy.data.objects[name].update_tag() # Blender's own update after the action evaluated it already: once more, alone start = time.perf_counter() faces = len(bpy.data.objects[name].evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # one whole evaluation: Subdivision and Solidify @@ -373,6 +394,10 @@ try: bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004) cut_faces = len(pauldron.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # with its one Boolean of six cutters times["rebuildUnderCuts"].append(time.perf_counter() - start) + for counting in (False, True): # the call alone: what count_folds adds to a rebuild under six cutters + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004, count_folds=counting) + times["rebuildCallCountingFolds" if counting else "rebuildCall"].append(time.perf_counter() - start) R["costs"] = {name: float(f"{statistics.median(values):.2g}") for name, values in times.items()} check("costs: the timed shells evaluated whole", faces == 3360 and cut_faces > 3360, [faces, cut_faces]) @@ -405,6 +430,9 @@ try: "sheet.creases[0].to must be a whole number from 0 to 5, not 6") refused("two weights on one edge", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 1}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]})}, "sheet.creases[1] gives an edge weight 0.5 that sheet.creases[0] gives 1") + mixed.modifiers["Kit Solidify"].show_viewport = False + refused("count_folds on a shell whose Kit Solidify is hidden", {"object_name": "Mixed", "sheet": SHEET, "count_folds": True}, "'Mixed' has its Kit Solidify hidden in viewports") + mixed.modifiers["Kit Solidify"].show_viewport = True refused("a sheet that is not JSON", {"object_name": "Mixed", "sheet": "{rings"}, "sheet is not JSON") refused("a sheet with an unknown key", {"object_name": "New", "sheet": json.dumps({**PAULDRON, "inside": [0, 0, 0]})}, "sheet has no key 'inside'") dense = {"rings": [[[j / 10, 0, i / 10] for j in range(34)] for i in range(34)]} diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 5523476..1ec749c 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -37,12 +37,17 @@ "detail": null }, { - "name": "shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", + "name": "shell-fold: count_folds counts no folded face on a creased ridge under the thickness its narrower facet holds, and the faces this script counts over it", "ok": true, "detail": null }, { - "name": "shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", + "name": "shell-fold: folded is null unless count_folds asks, whatever the wall does, and a ridge under a wall grown outward folds nowhere", + "ok": true, + "detail": null + }, + { + "name": "shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds", "ok": true, "detail": null }, @@ -81,6 +86,11 @@ "ok": true, "detail": null }, + { + "name": "shell-rebuild: count_folds under cutters counts the wall as this script does and leaves the stack shown, in order", + "ok": true, + "detail": null + }, { "name": "costs: the timed shells evaluated whole", "ok": true, @@ -131,6 +141,11 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: count_folds on a shell whose Kit Solidify is hidden", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a sheet that is not JSON", "ok": true, @@ -169,9 +184,34 @@ "solid": 0.027 }, "costs": { - "shell": 0.0074, - "evaluation": 0.0015, - "rebuildUnderCuts": 1.1 + "shell": 0.0059, + "shellCountingFolds": 0.0091, + "evaluation": 0.0022, + "rebuildUnderCuts": 1.7, + "rebuildCall": 1.6, + "rebuildCallCountingFolds": 1.6 + }, + "folds": { + "seeded": { + "5185 offset -1": [ + 2, + 2 + ], + "5101 offset 0": [ + 13, + 13 + ], + "5196 offset 1": [ + 4, + 4 + ] + }, + "held": { + "5185 offset -1": [ + 0, + 0 + ] + } }, "creaseRibs": "Operator brokkr_kitbash.ribs finished.", "ok": true diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 3faf4d3..1d66c66 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1558,34 +1558,6 @@ class SheetTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"): core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]}) - def test_fold_depths_are_the_narrower_facets_first_row_over_the_tangent(self): - """A ridge of two flat facets 1.0 and 0.3 wide, each tilted 45 degrees: the crease's fold depth is - (0.3 / 2^levels) / tan 45, the narrower facet's (F1: the wider facet's reach reads 0.25 at levels 2); the - facets fall away from their normals, a ridge, and turned over they are a valley; coplanar facets never fold.""" - h = math.sqrt(0.5) - - def wedge(sign, flat=False): - return core.sheet({"rings": [[[-h, y, 0.0 if flat else -sign * h], [0.0, y, 0.0], [0.3 * h, y, 0.0 if flat else -sign * 0.3 * h]] for y in (0.0, 0.5, 1.0)], - "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]}) - - pairs, depths, ridges, weights = core.fold_depths(wedge(1), 2) - crease = [k for k, pair in enumerate(pairs.tolist()) if pair in ([1, 4], [4, 7])] - self.assertEqual(len(pairs), 4) # the two crease edges and the middle ring's edge on each facet: an edge of the rim has one quad and no fold - self.assertEqual(len(crease), 2) - for k in crease: - self.assertAlmostEqual(depths[k], 0.075, places=12) - self.assertTrue(ridges[k]) - self.assertEqual(weights[k], 1.0) - self.assertTrue(all(math.isinf(depths[k]) and weights[k] == 0.0 for k in range(len(pairs)) if k not in crease)) # an edge inside a flat facet - self.assertAlmostEqual(core.fold_depths(wedge(1), 3)[1][crease[0]], 0.0375, places=12) # a level more halves the first row - valley = core.fold_depths(wedge(-1), 2) - self.assertAlmostEqual(valley[1][crease[0]], 0.075, places=12) - self.assertFalse(valley[2][crease[0]]) - self.assertTrue(np.isinf(core.fold_depths(wedge(1, flat=True), 2)[1]).all()) - steep = core.sheet({"rings": [[[-0.5, y, -math.sqrt(0.75)], [0.0, y, 0.0], [0.5, y, -math.sqrt(0.75)]] for y in (0.0, 1.0)]}) # facets 60 degrees off level, no crease stated - self.assertAlmostEqual(core.fold_depths(steep, 1)[1][0], 0.5 / math.tan(math.radians(60)), places=12) - self.assertEqual(core.fold_depths(steep, 1)[3][0], 0.0) - ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", @@ -1656,16 +1628,18 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) for row in self.document["actions"][4:]: - self.assertTrue(all(field["type"] in ("string", "number", "integer") for field in row["fields"]), row["name"]) + self.assertTrue(all(field["type"] in ("string", "number", "integer", "boolean") for field in row["fields"]), row["name"]) + self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"], + [("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"], [("brokkr_kitbash.shell", "levels")]) sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]}) shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet} - self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel")], [0.05, -1, 3, 0]) + self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False]) self.assertEqual(at.validate({**shell, "thickness": 0.001, "levels": 4}, host)["levels"], 4) for bad in ({**shell, "levels": 5}, {**shell, "levels": 2.5}, {**shell, "levels": 0}, {**shell, "thickness": 0.0005}, {**shell, "offset": 1.5}, {**shell, "bevel": 0.2}, {**shell, "sheet": "{" + " " * 32000}, {**shell, "sheet": ""}, {k: v for k, v in shell.items() if k != "sheet"}, {**shell, "object_name": "x" * 64}, - {**shell, "rings": []}): + {**shell, "rings": []}, {**shell, "count_folds": 1}): with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]): at.validate(bad, host) @@ -1749,9 +1723,9 @@ class OwnershipTests(unittest.TestCase): self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("), - (bodies["ribs"], "show_viewport = False")): + (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -1759,14 +1733,22 @@ class OwnershipTests(unittest.TestCase): for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) - shell = bodies["shell"] # shell evaluates nothing: Blender's own update after the action evaluates the plate once - for call in ("evaluated_of(", "evaluable(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"): + shell, count = bodies["shell"].split(" def folded_faces(") # shell evaluates nothing unless count_folds asks, and then the wall alone: no Boolean runs for it + shell, alone = shell.split(" def wall_alone(") + for call in ("evaluated_of(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"): self.assertNotIn(call, shell) + self.assertEqual((shell.count("evaluable("), shell.count("folded_faces("), shell.count("self.count_folds")), (1, 1, 2)) + self.assertLess(shell.index("if self.count_folds:"), shell.index("with self.wall_alone(obj):")) + self.assertLess(shell.index("with self.wall_alone(obj):"), shell.index("evaluable(")) + self.assertIn("self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None", shell) + self.assertLess(count.index("wall_alone(shell):"), count.index("evaluable(")) + self.assertEqual((count.count("evaluable("), count.count("to_mesh("), source.count("folded_faces("), source.count("wall_alone(")), (1, 1, 2, 3)) + self.assertLess(alone.index("finally:"), alone.index("modifier.show_viewport = True")) self.assertLess(shell.rindex("raise Refused("), shell.index("clear_geometry()")) # every refusal before any write self.assertLess(shell.index("core.sheet("), shell.index("clear_geometry()")) self.assertLess(shell.index("clear_geometry()"), shell.index("bpy.data.meshes.new(")) self.assertNotIn("objects.remove(", shell) # a rebuild rewrites the mesh in place: a new object would orphan its cutters and ribs - self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs + self.assertEqual(source.count("to_mesh("), 5) # boolean's report, in ribs the designed surface, the plate's two faces and the holed webs, and shell's fold count def test_only_ribs_writes_kit_ribs(self): """kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to