From ae56f48d701ade3b7541f751cc21e4adaee7cca3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:00:19 +0100 Subject: [PATCH 1/6] mesh_object refuses an object in no collection A deleted object a closure still points to stays in the file; attach, set_params, report, boolean and every polish operator found it by name. The refusal moves from close into mesh_object, which they all share (finding cut-kit-joints.s2.attach-onto-orphan-and-ends-first-unpinned, part 1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 3 --- surfaces/blender/brokkr_mesh_polish/__init__.py | 2 ++ 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 8edb244..3e19063 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -498,9 +498,6 @@ class BROKKR_KITBASH_OT_close(PolishOperator): other_part, other_built = built_part(other) if obj == other: raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") - for gone in (obj, other): - if not gone.users_collection: - raise Refused(f"{gone.name!r} is in no collection (a deleted object something still points to): a closure is between parts in the scene; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index 915ab5d..d1043c1 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -32,6 +32,8 @@ def mesh_object(name: str): obj = bpy.data.objects.get(name) if obj is None or obj.type != "MESH": raise Refused(f"No mesh object named {name!r}.") + if not obj.users_collection: + raise Refused(f"{name!r} is in no collection (a deleted object something still points to); nothing changed.") return obj From a3172c031b99673e64ac15980a3c3f60a5a8a591 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:02:34 +0100 Subject: [PATCH 2/6] brokkr_kitbash: one Boolean modifier per operation over a collection of cutters, on any mesh The per-cutter modifier (Kit Boolean , operand OBJECT) is gone. A target carries at most Kit Difference, Kit Union and Kit Intersect, each Exact with self-intersection, each over a collection in no scene; operation_collection is the one way a cutter comes to cut, and booleans() reads the three collections. boolean takes any rigid mesh target; apply removes the collections it emptied of users and leaves the cutter objects. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 106 ++++++++++++------ .../blender/tests/live/kitbash_assembly.py | 29 ++--- surfaces/blender/tests/test_kitbash.py | 6 +- 3 files changed, 92 insertions(+), 49 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 3e19063..cb5b956 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -14,12 +14,17 @@ params). A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' -params by core.mate; attach and set_params write it, and a report says how far the child stands from it. A boolean -belongs to its Boolean modifier on the target (the modifier's object is the cutter; its name is a label). kit_baked +params by core.mate; attach and set_params write it, and a report says how far the child stands from it. kit_baked says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). +A Boolean belongs to the target: any mesh, kit part or not, carries at most one Exact Boolean modifier per +operation (Kit Difference, Kit Union, Kit Intersect, evaluated in that order above the Bevel), and that modifier's +collection holds the cutters. One Boolean over a collection of eight cutters costs what one cutter costs; eight +modifiers cost seven times that (docs/kitbash.md). Which cutters cut a target is stored nowhere else: the +collection's name is a label, and it is linked to no scene. + 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 @@ -49,7 +54,7 @@ SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_rol CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" -BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object +OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates @@ -95,17 +100,23 @@ def sync_bevel(obj, width: float) -> None: RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation -def kit_part_of(obj, kits=None): - """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is - not rigid: its socket frames would not be frames, and its size would have a second owner. `kits` is a dict one - call may pass to read each kit file once while it reads many parts; nothing keeps it between calls.""" - if PART not in obj: - raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") +def rigid(obj) -> None: + """Refuses an object whose world transform scales, mirrors or shears: a frame under it (a socket, a cutter) would + not be a frame, and a kit part's size would have a second owner.""" turn = np.array(obj.matrix_world)[:3, :3] if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0: scale = ", ".join(f"{s:.4g}" for s in obj.matrix_world.to_scale()) raise Refused(f"{obj.name!r} is scaled, mirrored or sheared in the world (scale {scale}): a kit part's size is its params. " "Set its scale, and its parents', to 1 (setObjectTransform) and resize it with set_params.") + + +def kit_part_of(obj, kits=None): + """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is + not rigid (rigid). `kits` is a dict one call may pass to read each kit file once while it reads many parts; + nothing keeps it between calls.""" + if PART not in obj: + raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + rigid(obj) try: stored = json.loads(obj.get(PARAMS, "{}")) except ValueError: @@ -298,13 +309,46 @@ def own_mesh(obj, doing: str) -> None: "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") +def operation_collection(target, operation: str, make: bool = False): + """The collection whose mesh objects the target's Kit Boolean modifier cuts with, or None when the + target has no such modifier. With `make`, the modifier (Exact, self-intersection on, materials transferred) and + its collection are made: the modifier goes above the Kit Bevel and above the Kit modifier of any later + operation, so the stack reads difference, union, intersect, bevel. The one way a cutter comes to cut a target: + boolean and cut add to this collection, and booleans() reads it.""" + name = "Kit " + operation.title() + modifier = target.modifiers.get(name) + if modifier is None: + if not make: + return None + modifier = target.modifiers.new(name, "BOOLEAN") + modifier.operation, modifier.operand_type, modifier.solver, modifier.use_self = operation, "COLLECTION", "EXACT", True + modifier.material_mode = "TRANSFER" # with the default (INDEX) the result gains an empty material slot for a cutter that has no materials + names = [m.name for m in target.modifiers] + below = [names.index(n) for n in [BEVEL] + ["Kit " + o.title() for o in OPERATIONS[OPERATIONS.index(operation) + 1:]] if n in names] + if below: # cut first, then bevel the cut's edges with the rest + target.modifiers.move(len(names) - 1, min(below)) + if modifier.collection is None and make: + modifier.collection = bpy.data.collections.new(f"{target.name} {operation.lower()}") + return modifier.collection + + def booleans(obj) -> list: - return [{"cutter": m.object.name if m.object else None, "operation": m.operation} for m in obj.modifiers if m.type == "BOOLEAN"] + """What cuts a target, as {cutter, operation} rows: difference, then union, then intersect, each in the order + its cutters were added.""" + return [{"cutter": cutter.name, "operation": operation} for operation in OPERATIONS + for cutter in getattr(operation_collection(obj, operation), "objects", ())] + + +def uncut(target, cutter) -> None: + """Refuses a cutter that already cuts the target, under any operation.""" + for operation in OPERATIONS: + if cutter in getattr(operation_collection(target, operation), "objects", ())[:]: + raise Refused(f"{cutter.name!r} already cuts {target.name!r} (its Kit {operation.title()} modifier's collection); nothing changed.") def evaluated_of(context, obj): - """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs about a second a part, so only - boolean and apply call this; no report does.""" + """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs from a few tenths of a second (a + kit part) to a few seconds (a subdivided shell), so only cut, boolean and apply call this; no report does.""" depsgraph = context.evaluated_depsgraph_get() return depsgraph, obj.evaluated_get(depsgraph) @@ -512,36 +556,25 @@ class BROKKR_KITBASH_OT_close(PolishOperator): class BROKKR_KITBASH_OT_boolean(PolishOperator): - """Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit - parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result""" + """Cut a mesh object, a kit part or any other, with another mesh object: the cutter joins the collection of the + target's one live Boolean modifier for the operation (Exact, with self-intersection: kit parts are overlapping + shells), above the Bevel; evaluates the target once and reports the result""" bl_idname = "brokkr_kitbash.boolean" bl_label = "Boolean Kit Part" - object_name: bpy.props.StringProperty(name="Object", description="The kit part that is cut") + object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") cutter: bpy.props.StringProperty(name="Cutter", description="Any other mesh object; it is not changed") operation: bpy.props.EnumProperty(name="Operation", default="DIFFERENCE", items=[ ("DIFFERENCE", "Difference", ""), ("UNION", "Union", ""), ("INTERSECT", "Intersect", "")]) @kit_work def work(self, context): - obj = mesh_object(self.object_name) - part, built = built_part(obj) - cutter = bpy.data.objects.get(self.cutter) - if cutter is None or cutter.type != "MESH": - raise Refused(f"No mesh object named {self.cutter!r} to cut with; nothing changed.") + obj, cutter = mesh_object(self.object_name), mesh_object(self.cutter) if cutter == obj: raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.") - if any(m.type == "BOOLEAN" and m.object == cutter for m in obj.modifiers): - raise Refused(f"{cutter.name!r} is already the object of a Boolean on {obj.name!r}; nothing changed.") - modifier = obj.modifiers.new(BOOLEAN + cutter.name, "BOOLEAN") - modifier.operation, modifier.object = self.operation, cutter - # TRANSFER: with the default (INDEX) the result gains an empty material slot for a cutter that has no materials - modifier.solver = "EXACT" - modifier.use_self = True - modifier.material_mode = "TRANSFER" - names = [m.name for m in obj.modifiers] - if BEVEL in names: # cut first, then bevel the cut's edges with the rest - obj.modifiers.move(len(names) - 1, names.index(BEVEL)) - report = part_report(obj, part, built) + report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} + rigid(obj) + uncut(obj, cutter) + operation_collection(obj, self.operation, True).objects.link(cutter) _, evaluated = evaluated_of(context, obj) report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh()) evaluated.to_mesh_clear() @@ -549,8 +582,9 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): class BROKKR_KITBASH_OT_apply(PolishOperator): - """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes, its - material slots stay, and it is marked baked; its sockets and connections stay as they are""" + """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with + the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections + stay as they are, and so do the cutter objects""" bl_idname = "brokkr_kitbash.apply" bl_label = "Apply Kit Part" object_name: bpy.props.StringProperty(name="Object") @@ -572,8 +606,12 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material baked.polygons.foreach_set("material_index", np.maximum(index, 0)) old, name = obj.data, obj.data.name + held = [found for found in (operation_collection(obj, operation) for operation in OPERATIONS) if found is not None] obj.data = baked obj.modifiers.clear() + for collection in held: # a collection another object's modifier still reads (a copied part) stays + if collection.users == 0: + bpy.data.collections.remove(collection) if old.users == 0: bpy.data.meshes.remove(old) baked.name = name diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index d5a4a00..1b2b5aa 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params, -attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and apply with its material slots. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- @@ -558,10 +558,12 @@ 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 Boolean Box") -check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", - receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "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", "OBJECT", 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 @@ -572,18 +574,17 @@ check("boolean reports the evaluated mesh, with less volume than the uncut tank 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, 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' is already the object of a Boolean on 'Tank'") + "'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'") -refused("boolean on a mesh that is not a kit part", "brokkr_kitbash.boolean", {"object_name": "Plain", "cutter": "Box"}, "'Plain' is not a kit part") 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 Boolean Box", "Kit Bevel"] and tank.modifiers["Kit Boolean Box"].object == box + 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]) @@ -593,14 +594,15 @@ 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 = tank.data.name, len(bpy.data.meshes) +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"], [receipt["message"], baked, shown]) + 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()))]) @@ -622,8 +624,9 @@ send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], 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 stack in the order they came, both above the Bevel", receipt["status"] == "accepted" - and [m.name for m in plate.modifiers] == ["Kit Boolean Slot", "Kit Boolean Hole", "Kit Bevel"] +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"), diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 7300431..44f97d0 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -834,7 +834,8 @@ class OwnershipTests(unittest.TestCase): r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner - r"SCREW|\"ARRAY\"|spin\(") # core makes every vertex: no modifier or bmesh op makes kit geometry + r"SCREW|\"ARRAY\"|spin\(", # core makes every vertex: no modifier or bmesh op makes kit geometry + r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT") # cutters cut through one collection Boolean per operation, never a modifier each CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -889,7 +890,8 @@ class OwnershipTests(unittest.TestCase): def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', - 'obj.modifiers.new("Turn", "SCREW")') + 'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"') + self.assertIsNotNone(re.search(self.PACKAGE[6], 'obj.modifiers.new("Kit Boolean " + cutter.name, "BOOLEAN")')) for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"): self.assertIsNotNone(re.search(self.PACKAGE[5], text)) self.assertEqual(len(planted), len(self.PACKAGE)) From 972d51e1ee0e85d1abdaf9c2bd2c79d085d1c368 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:03:48 +0100 Subject: [PATCH 3/6] brokkr_kitbash: parts of two kits mate by the socket types both declare alike core.joint no longer refuses parts of different kits. mate_refusal takes the child kit's socketTypes and the two kit names: a type the child's kit does not declare with the parent kit's match is refused naming both kits; then the shared size rule. One kit reads as before. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 26 +++++++++++---------- surfaces/blender/brokkr_kitbash/core.py | 21 ++++++++++------- surfaces/blender/tests/test_kitbash.py | 26 ++++++++++++++++++--- 3 files changed, 50 insertions(+), 23 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index cb5b956..52a9ce0 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -199,14 +199,16 @@ def free(part, socket: str) -> None: def mated(parent, parent_part, parent_built, child, child_part, child_built, stated, how="on"): """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names - it: a roll that is not a number, parts of two kits, a socket name a part does not have, or sockets - core.mate_refusal will not mate. A closure is checked here too (how "closing on"), the part it names as the - parent.""" + it: a roll that is not a number, a socket name a part does not have, or sockets core.mate_refusal will not + mate. The parts may be of two kits: they mate when both kits declare the socket's type alike. A closure is + checked here too (how "closing on"), the part it names as the parent.""" if stated[2] is None: raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") try: sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) - refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets) + kits = (parent_part["kit"], child_part["kit"]) + refusal = core.mate_refusal(core.load_kit(kits[0])["socketTypes"], *sockets, + None if kits[0] == kits[1] else core.load_kit(kits[1])["socketTypes"], kits) except core.KitError as error: refusal = str(error) if refusal: @@ -221,8 +223,8 @@ def seat(child, basis) -> None: def connection_report(obj, part, built): - """None for a part that states no connection, else what it states and whether it holds: the parent is a part - of the same kit, both sockets exist, the roll is a number, the parent inverse is the identity and the child + """None for a part that states no connection, else what it states and whether it holds: the parent is a kit + part, both sockets exist, the roll is a number, the parent inverse is the identity and the child stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again.""" stated = link(obj) @@ -244,8 +246,8 @@ def connection_report(obj, part, built): def closure_report(obj, part, built, held=None, kits=None): """None for a part that states no closure, else what it states, whether it holds and, when it does not, why - not: the other part is gone (`to` null); it is not a part this one can be read against (not a kit part, of - another kit, scaled, or without that socket); another part's closure names the same socket (a duplicated + not: the other part is gone (`to` null); it is not a part this one can be read against (not a kit part, + scaled, or without that socket); another part's closure names the same socket (a duplicated closing part); or the two sockets stand more than HELD from meeting (core.closure_residual). Derived at each report; stored nowhere. `held` is closers() and `kits` kit_part_of's, for a caller that reports many.""" stated = closure(obj) @@ -464,8 +466,8 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): class BROKKR_KITBASH_OT_attach(PolishOperator): - """Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, - normals opposed, turned by roll about the parent socket's normal""" + """Seat a socket of a kit part on a socket of another part, of its kit or of any kit whose socket types agree, + and parent it there: origins together, normals opposed, turned by roll about the parent socket's normal""" bl_idname = "brokkr_kitbash.attach" bl_label = "Attach Kit Part" object_name: bpy.props.StringProperty(name="Object", description="The child: the part that moves") @@ -525,8 +527,8 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): class BROKKR_KITBASH_OT_close(PolishOperator): - """State that a socket of a kit part meets a socket of another part of its kit, closing a loop the tree of - connections cannot: accepted only when the two already meet, origins together and normals opposed, and it + """State that a socket of a kit part meets a socket of another part, of its kit or of any kit whose socket types + agree, closing a loop the tree of connections cannot: accepted only when the two already meet, origins together and normals opposed, and it moves nothing""" bl_idname = "brokkr_kitbash.close" bl_label = "Close Kit Loop" diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 3f7c3cf..5713ab6 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -11,7 +11,8 @@ whitelist; nothing in a kit is ever run as Python. built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, sharp, shell_count, sockets Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual -(how far a placed child stands from its mate). closure_residual is how far two sockets stand from meeting as a pin, +(how far a placed child stands from its mate). Socket types are a vocabulary kits share: parts of two kits mate when +both kits declare the socket's type with the same match rule. closure_residual is how far two sockets stand from meeting as a pin, whatever the roll: what closes a loop the tree of connections cannot state. Every refusal is a KitError whose message names the kit, part and field. @@ -633,13 +634,20 @@ def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it -def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> str | None: +def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child_types: dict | None = None, kits=("the parent's", "the child's")) -> str | None: """None when the two sockets may mate, else a sentence naming both: they are of one type, and their sizes - agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent).""" + agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent). + kit_types is the socketTypes of the parent's kit. For parts of two kits, child_types is the socketTypes of the + child's and `kits` the two kits' names: socket types are a vocabulary kits share, and the two sockets mate only + when the child's kit declares the type with the same match.""" p, c = parent_socket, child_socket both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})" if p["type"] != c["type"]: return f"{both} are of different types" + if child_types is not None and child_types.get(c["type"], {}).get("match") != kit_types[p["type"]]["match"]: + theirs = child_types.get(c["type"], {}).get("match") + return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with match {kit_types[p['type']]['match']!r} and kit {kits[1]!r} " + f"{'with match ' + repr(theirs) if theirs else 'does not declare it'}; parts of two kits mate by socket types both declare alike") if kit_types[p["type"]]["match"] == "equal": if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK): return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)" @@ -649,11 +657,8 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> st def joint(parent_part: dict, parent_built: Built, parent_socket: str, child_part: dict, child_built: Built, child_socket: str): - """(parent socket, child socket) of a connection between two built parts, by socket name. Refuses parts of - different kits (socket types belong to a kit) and a name the part has no socket for.""" - if parent_part["kit"] != child_part["kit"]: - raise KitError(f"part {child_part['name']!r} is of kit {child_part['kit']!r} and part {parent_part['name']!r} of kit " - f"{parent_part['kit']!r}: socket types belong to a kit, so parts of different kits do not mate") + """(parent socket, child socket) of a connection between two built parts, of one kit or of two, by socket name. + Refuses a name the part has no socket for. Whether the two may mate is mate_refusal's: their socket types decide.""" found = [] for part, built, name in ((parent_part, parent_built, parent_socket), (child_part, child_built, child_socket)): match = [s for s in built.sockets if s["name"] == name] diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 44f97d0..fc9fd43 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -724,6 +724,24 @@ class MateTests(unittest.TestCase): self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3))) self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 * (1 + 2.2e-6)))) + def test_kits_mate_by_the_socket_types_they_share(self): + """cross-kit-types. Mutant S5 (mate_refusal ignores the child kit's match): a mount another kit declares 'equal' mates.""" + types = self.kit["socketTypes"] + socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 + hydraulic = copy.deepcopy(types) + for kind, big, small in (("flange", 100.0, 99.0), ("pivot", 0.2, 0.198), ("mount", 0.3, 0.1)): + self.assertIsNone(core.mate_refusal(types, socket("p", kind, big), socket("c", kind, small), hydraulic, ("mechanical", "hydraulic"))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", "flange", 100.0), socket("c", "flange", 98.0), hydraulic, ("mechanical", "hydraulic"))) + odd = {**hydraulic, "mount": {"match": "equal", "doc": ""}} + self.assertRegex(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3), odd, ("mechanical", "odd")), + r"kit 'mechanical' declares socket type 'mount' with match 'fits' and kit 'odd' with match 'equal'; parts of two kits mate by socket types both declare alike") + self.assertRegex(core.mate_refusal(odd, socket("p", "mount", 0.3), socket("c", "mount", 0.3), types, ("odd", "mechanical")), + r"kit 'odd' declares socket type 'mount' with match 'equal' and kit 'mechanical' with match 'fits'") + self.assertRegex(core.mate_refusal(types, socket("p", "pivot", 0.2), socket("c", "pivot", 0.2), {"mount": types["mount"]}, ("mechanical", "bare")), + r"kit 'mechanical' declares socket type 'pivot' with match 'equal' and kit 'bare' does not declare it") + self.assertIn("are of different types", core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1), odd, ("mechanical", "odd"))) + self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3), None)) # one kit: as before + def test_the_kit_s_own_flanges_do_not_meet_everywhere(self): """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate face to face.""" @@ -757,14 +775,16 @@ class MateTests(unittest.TestCase): self.assertEqual([s["matrix"][:3, 2].tolist() for s in reducer.sockets], [[0.0, 0.0, -1.0], [0.0, 0.0, 1.0]]) def test_a_joint_is_two_named_sockets_of_one_kit(self): - """The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals.""" + """A joint of one kit or of two (what may mate is mate_refusal's), and the unknown-socket refusals.""" parts = self.kit["parts"] tank, fitting = core.build(parts["tank"]), core.build(parts["pipe_fitting"]) sp, sc = core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "a") self.assertEqual((sp["name"], sc["name"]), ("port_b", "a")) other = {**parts["pipe_fitting"], "kit": "hydraulic"} - with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"): - core.joint(parts["tank"], tank, "port_b", other, fitting, "a") + sp, sc = core.joint(parts["tank"], tank, "port_b", other, fitting, "a") + self.assertEqual((sp["name"], sp["size"], sc["name"], sc["size"]), ("port_b", tank.sockets[1]["size"], "a", fitting.sockets[0]["size"])) + with self.assertRaisesRegex(core.KitError, "kit 'hydraulic' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): + core.joint(parts["tank"], tank, "port_b", other, fitting, "d") with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle, lug_a, lug_b, lug_a_back, lug_b_back"): core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a") with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): From c6aeeff52ba67a8ce6d087dbc53b11de47f0d196 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:35:14 +0100 Subject: [PATCH 4/6] brokkr_kitbash.cut: cut any mesh at a ray with a part of the cutters kit whose floor is a socket kits/cutters.v0.json: box, cyl, slot and slab, spanning z from -depth to +lift; box, cyl and slot carry a floor socket (mount) on the bottom of the recess. core.surface_frame is the cutter's frame at the hit. cut casts at the target with its Kit Booleans off, places the cutter as a kit part parented to the target under an identity parent inverse and adds it to the difference collection: the cutter object owns the recess frame and size, and machinery attaches to its floor with the ordinary attach. tests/live/kitbash_shell.py: cut on a cage that is not a kit part, a vent on a floor, the three Boolean modifiers, the refusals, an object in no collection, and the ends-first order of a set_params report's closures (finding cut-kit-joints.s2.attach-onto-orphan-and-ends-first-unpinned, part 2). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 74 +++- .../brokkr_kitbash/brokkr_actions.json | 126 +++++- surfaces/blender/brokkr_kitbash/core.py | 22 +- .../brokkr_kitbash/kits/cutters.v0.json | 80 ++++ surfaces/blender/docs/kitbash.md | 108 +++-- surfaces/blender/tests/live/kitbash.py | 4 +- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 4 +- .../tests/live/kitbash_assembly.result.json | 15 +- surfaces/blender/tests/live/kitbash_shell.py | 371 ++++++++++++++++++ .../tests/live/kitbash_shell.result.json | 279 +++++++++++++ surfaces/blender/tests/test_kitbash.py | 171 +++++++- 12 files changed, 1204 insertions(+), 53 deletions(-) create mode 100644 surfaces/blender/brokkr_kitbash/kits/cutters.v0.json create mode 100644 surfaces/blender/tests/live/kitbash_shell.py create mode 100644 surfaces/blender/tests/live/kitbash_shell.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 52a9ce0..430fde2 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1,4 +1,5 @@ -"""Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them, and bake them. +"""Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them and any other +mesh, and bake them. A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base, Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents @@ -25,6 +26,11 @@ collection holds the cutters. One Boolean over a collection of eight cutters cos modifiers cost seven times that (docs/kitbash.md). Which cutters cut a target is stored nowhere else: the collection's name is a label, and it is linked to no scene. +cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters kit, parented to the target under an +identity parent inverse: its matrix_basis is the recess frame and its params the recess size, so moving or resizing +the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches +to the floor socket with the ordinary attach. + 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 @@ -39,7 +45,8 @@ import math import bmesh import bpy import numpy as np -from mathutils import Matrix +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree try: from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object @@ -54,6 +61,7 @@ SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_rol CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" +CUTTERS = "cutters" # the kit whose parts cut places OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates @@ -583,6 +591,65 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): return report +class BROKKR_KITBASH_OT_cut(PolishOperator): + """Cut a mesh object, a kit part or any other, where a ray meets it: places a part of the cutters kit on the + surface there (z the surface normal, y the projection of up, turned by roll), parented to the target, and adds it + to the target's difference Boolean; the cutter's floor socket is where machinery attaches""" + bl_idname = "brokkr_kitbash.cut" + bl_label = "Cut At Ray" + object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") + cutter_name: bpy.props.StringProperty(name="Cutter", description="The new cutter object's name") + part: bpy.props.EnumProperty(name="Part", default="box", items=[("box", "Box", ""), ("cyl", "Cylinder", ""), ("slot", "Slot", ""), ("slab", "Slab", "")]) + params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest take the cutter part's defaults") + origin_x: bpy.props.FloatProperty(name="Origin X", description="The ray's origin, in the target's own frame") + origin_y: bpy.props.FloatProperty(name="Origin Y") + origin_z: bpy.props.FloatProperty(name="Origin Z") + direction_x: bpy.props.FloatProperty(name="Direction X", description="The ray's direction, in the target's own frame") + direction_y: bpy.props.FloatProperty(name="Direction Y") + direction_z: bpy.props.FloatProperty(name="Direction Z") + up_x: bpy.props.FloatProperty(name="Up X", default=0.0, description="Which way the cutter's y points, in the target's own frame") + up_y: bpy.props.FloatProperty(name="Up Y", default=0.0) + up_z: bpy.props.FloatProperty(name="Up Z", default=1.0) + roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, description="Degrees about the surface normal, right-handed") + + @kit_work + def work(self, context): + target = mesh_object(self.object_name) + rigid(target) + if self.cutter_name in bpy.data.objects: + raise Refused(f"An object named {self.cutter_name!r} exists; nothing changed.") + part = core.part(core.load_kit(CUTTERS), self.part) + built = core.build(part, core.parse_params(self.params)) + origin, direction = Vector((self.origin_x, self.origin_y, self.origin_z)), Vector((self.direction_x, self.direction_y, self.direction_z)) + if direction.length == 0.0: + raise Refused("The ray's direction is zero; nothing changed.") + cuts = [m for m in (target.modifiers.get("Kit " + operation.title()) for operation in OPERATIONS) if m is not None and m.show_viewport] + try: # the surface as designed, not as already cut: a second cut on the ray of a through bay lands where the first did + for modifier in cuts: + modifier.show_viewport = False + depsgraph, _ = evaluated_of(context, target) + hit, normal, _, _ = BVHTree.FromObject(target, depsgraph).ray_cast(origin, direction.normalized()) + finally: + for modifier in cuts: + modifier.show_viewport = True + if hit is None: + raise Refused(f"The ray from {tuple(round(v, 6) for v in origin)} along {tuple(round(v, 6) for v in direction)} misses {target.name!r}; nothing changed.") + if normal.dot(direction) > 0: + normal = -normal + frame = core.surface_frame(hit, normal, (self.up_x, self.up_y, self.up_z), self.roll) + mesh = bpy.data.meshes.new(self.cutter_name) + write_mesh(mesh, built) + cutter = bpy.data.objects.new(self.cutter_name, mesh) + context.scene.collection.objects.link(cutter) + sync_bevel(cutter, built.bevel) + cutter[KIT], cutter[PART], cutter[PARAMS] = part["kit"], part["name"], json.dumps(built.params) + cutter.parent = target + cutter.matrix_world = target.matrix_world @ Matrix(frame.tolist()) # read by the report below; no depsgraph update, which would evaluate the Boolean + seat(cutter, frame) + operation_collection(target, "DIFFERENCE", True).objects.link(cutter) + return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)} + + class BROKKR_KITBASH_OT_apply(PolishOperator): """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections @@ -651,7 +718,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_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply) + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, + BROKKR_KITBASH_OT_apply) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 6bd1ba7..cf8de59 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -109,7 +109,7 @@ }, { "name": "brokkr_kitbash.attach", - "doc": "Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.", + "doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -176,7 +176,7 @@ }, { "name": "brokkr_kitbash.close", - "doc": "Close a loop: state that a socket of a kit part meets a socket of another part of its kit, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.", + "doc": "Close a loop: state that a socket of a kit part meets a socket of a part of any kit whose socket types agree, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -219,7 +219,7 @@ }, { "name": "brokkr_kitbash.boolean", - "doc": "Cut a kit part with another mesh object through a live Boolean modifier (Exact, self-intersection on) above its Bevel. Evaluates the part once, about a second: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", + "doc": "Cut a mesh, a kit part or any other, with another mesh object: the cutter joins the collection of the target's one live Boolean modifier for the operation (Exact, self-intersection on; difference, then union, then intersect, above its Bevel). Evaluates the target once, from a few tenths of a second to a few seconds: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -230,7 +230,7 @@ "required": true, "minLength": 1, "maxLength": 63, - "doc": "the kit part that is cut" + "doc": "the mesh that is cut: a kit part or any mesh" }, { "name": "cutter", @@ -252,6 +252,124 @@ } ] }, + { + "name": "brokkr_kitbash.cut", + "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Does not evaluate the Boolean itself (boolean does, and reports it). Reports the cutter with its sockets, and booleans.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the mesh that is cut: a kit part or any mesh, not scaled" + }, + { + "name": "cutter_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the new cutter object's name; refused when an object has it" + }, + { + "name": "part", + "type": "string", + "required": true, + "enum": [ + "box", + "cyl", + "slot", + "slab" + ], + "doc": "a part of the cutters kit" + }, + { + "name": "params", + "type": "string", + "maxLength": 4000, + "default": "", + "doc": "name=value; name=value ... depth below the surface, lift above it, and the part's own; the rest take its defaults" + }, + { + "name": "origin_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true, + "doc": "the ray's origin, in the target's own frame" + }, + { + "name": "origin_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "origin_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "direction_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true, + "doc": "the ray's direction, in the target's own frame; any length but zero" + }, + { + "name": "direction_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "direction_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "up_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0, + "doc": "which way the cutter's y points, in the target's own frame; refused along the surface normal" + }, + { + "name": "up_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + }, + { + "name": "up_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 1 + }, + { + "name": "roll", + "type": "number", + "minimum": -360, + "maximum": 360, + "default": 0, + "doc": "degrees about the surface normal, right-handed" + } + ] + }, { "name": "brokkr_kitbash.apply", "doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers and a mesh another object shares.", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 5713ab6..066f233 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1,7 +1,8 @@ """The kit format: what a kit document may say, and the geometry and socket frames a part and its params produce. numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data -(kits/.v0.json beside this file). A part is a list of shapes (tube, box, lathe, and a repeat of one of +(kits/.v0.json beside this file: mechanical, the machine parts, and cutters, the parts brokkr_kitbash.cut +places to cut a mesh, each with its recess floor as a socket). A part is a list of shapes (tube, box, lathe, and a repeat of one of them, a step apart or turned about an axis) whose numbers may be expressions over the part's params, and a list of sockets, each a frame on one of the part's flat faces. A lathe profile point may be marked sharp: its ring of edges is then a crease (Built.sharp). An expression is parsed with ast.parse and walked against a @@ -12,7 +13,8 @@ whitelist; nothing in a kit is ever run as Python. Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual (how far a placed child stands from its mate). Socket types are a vocabulary kits share: parts of two kits mate when -both kits declare the socket's type with the same match rule. closure_residual is how far two sockets stand from meeting as a pin, +both kits declare the socket's type with the same match rule. surface_frame is the frame a cutter takes where a ray +met a surface. closure_residual is how far two sockets stand from meeting as a pin, whatever the roll: what closes a loop the tree of connections cannot state. Every refusal is a KitError whose message names the kit, part and field. @@ -609,6 +611,22 @@ def _roll(degrees: float) -> np.ndarray: return turn +def surface_frame(point, normal, up, roll_degrees: float = 0.0) -> np.ndarray: + """The 4x4 frame at a point of a surface: z the unit normal, y the unit projection of `up` off z, x = y cross z, + then turned roll_degrees about z (right-handed, as mate's roll). Refuses a zero normal and an up along it.""" + point, z, up = (np.asarray(v, dtype=np.float64) for v in (point, normal, up)) + if not np.isfinite(z).all() or not np.linalg.norm(z) > 0: + raise KitError(f"normal {normal} has no direction") + z = z / np.linalg.norm(z) + y = up - z * (up @ z) + if not np.isfinite(y).all() or not np.linalg.norm(y) > 1e-6 * np.linalg.norm(up): + raise KitError(f"up {up.tolist()} runs along the surface normal {np.round(z, 6).tolist()} (or is zero): give an up that crosses it") + y = y / np.linalg.norm(y) + frame = np.eye(4) + frame[:3, 0], frame[:3, 1], frame[:3, 2], frame[:3, 3] = np.cross(y, z), y, z, point + return frame @ _roll(roll_degrees) + + def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0) -> np.ndarray: """The child's 4x4 in its parent's frame that seats child_socket on parent_socket: origins together, normals opposed, the child turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up).""" diff --git a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json new file mode 100644 index 0000000..0677a9e --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json @@ -0,0 +1,80 @@ +{ + "schema": "brokkr.kit.v0", + "kit": "cutters", + "doc": "Cutters for brokkr_kitbash.cut: each part spans z from -depth to +lift in its frame, whose origin is where the ray met the surface and whose z is the surface normal; metres.", + "socketTypes": { + "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"} + }, + "parts": [ + { + "name": "box", + "doc": "Rectangular recess or bay. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "params": [ + {"name": "width", "type": "number", "min": 0.005, "max": 8, "default": 0.2, "doc": "across (x)"}, + {"name": "height", "type": "number", "min": 0.005, "max": 8, "default": 0.2, "doc": "along up (y)"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies in a row along y, centred on the frame (roll 90 turns the row along x)"}, + {"name": "pitch", "type": "number", "min": 0, "max": 4, "default": 0, "doc": "distance between copies"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "box", "size": ["width", "height", "depth+lift"], "at": [0, "-(count-1)*pitch/2", "(lift-depth)/2"]}} + ], + "sockets": [ + {"name": "floor", "type": "mount", "size": "min(width,height)", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "cyl", + "doc": "Round recess or opening. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "params": [ + {"name": "r", "type": "number", "min": 0.0025, "max": 4, "default": 0.1, "doc": "radius"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies in a row along y, centred on the frame (roll 90 turns the row along x)"}, + {"name": "pitch", "type": "number", "min": 0, "max": 4, "default": 0, "doc": "distance between copies"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "r", "r1": "r", "length": "depth+lift", "segments": 32, "at": [0, "-(count-1)*pitch/2", "-depth"]}} + ], + "sockets": [ + {"name": "floor", "type": "mount", "size": "2*r", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "slot", + "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "params": [ + {"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"}, + {"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies in a row along y, centred on the frame (roll 90 turns the row along x)"}, + {"name": "pitch", "type": "number", "min": 0, "max": 4, "default": 0, "doc": "distance between copies"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "box", "size": ["width-height", "height", "depth+lift"], "at": [0, "-(count-1)*pitch/2", "(lift-depth)/2"]}}, + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["-(width-height)/2", "-(count-1)*pitch/2", "-depth"]}}, + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}} + ], + "sockets": [ + {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "slab", + "doc": "Panel break: a thin slab standing on the surface normal, long along y; roll turns it about the normal. No socket.", + "params": [ + {"name": "gap", "type": "number", "min": 0.002, "max": 0.2, "default": 0.02, "doc": "the break's width (x)"}, + {"name": "length", "type": "number", "min": 0.01, "max": 8, "default": 2, "doc": "along y"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"} + ], + "shapes": [ + {"shape": "box", "size": ["gap", "length", "depth+lift"], "at": [0, 0, "(lift-depth)/2"]} + ], + "sockets": [ + ] + } + ] +} diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index b46d57a..26829ce 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -139,8 +139,12 @@ matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach` and `set_params` write it; nothing else should. -**What may mate** (`core.mate_refusal`): two sockets of one kit and one type whose sizes agree as the type's -`match` says: `equal` within 1 percent of the larger, `fits` with the child at most the parent. `attach` also +**What may mate** (`core.mate_refusal`): two sockets of one type whose sizes agree as the type's +`match` says: `equal` within 1 percent of the larger, `fits` with the child at most the parent. Socket types are a +vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match` +(`cutters` declares `mount` as `mechanical` does, so a vent seats on a recess floor), and are refused, naming both +kits and the type, when one does not declare it or declares it otherwise. KSP's attach nodes and LDraw's snap +types are connector vocabularies of this kind: global, matched by type and size. `attach` also refuses, changing nothing: - a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not @@ -190,7 +194,7 @@ A part's report carries `closure`: `null`, or `residual` is the larger of the largest difference between the two origins and the largest entry of the sum of the two normals; `holds` is true when it is at most 1e-5 and nothing below applies. When it does not hold, `reason` says why in a sentence: the other part is gone (`to` is then `null`); the other part cannot be read -against (not a kit part, of another kit, scaled by hand, or without that socket; `residual` is then `null`); +against (not a kit part, scaled by hand, or without that socket; `residual` is then `null`); another part's closure names the same socket, which a duplicated closing part leaves behind and which makes both read not held until one is detached; or the two sockets stand apart. A closure is never seated. `set_params` on either end refuses a change after which the two sockets may no longer mate (a pin of another size), naming the closure. A change that only @@ -215,7 +219,7 @@ child. Reports show it: a part's `connection` is `null`, or ``` `residual` is the largest entry of the difference between the socket's world frame and the frame its mate asks -for; `holds` is true when the parent is a kit part of the same kit, both sockets exist, the roll is a number, +for; `holds` is true when the parent is a kit part, both sockets exist, the roll is a number, the parent inverse is the identity and the residual is at most 1e-5. The next `set_params` on the child or on its parent (with any param, even at its current value) seats it again. A child whose parent was cleared or replaced by something that is not a kit part reads `holds` false with a `null` residual, and `set_params` @@ -224,32 +228,88 @@ A `kit_roll` that is not a finite number (only a hand can write one) reads `roll `set_params` on the child or its parent refuses it and leaves it as written: `detach` the child and `attach` it again. `detach` keeps the part where it stands in the world and leaves the parts attached to it attached. -**`boolean`** adds a Boolean modifier named `Kit Boolean ` to a kit part, above its `Kit Bevel`, so the -cut's edges are bevelled with the rest. The modifier's object is the cutter; the name is a label. The solver is -always Exact with self-intersection on: a kit part is several overlapping closed shells, and without it the -shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap and the -barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that +**`boolean`** cuts a mesh, a kit part or any other, with another mesh object. A target carries at most one +Boolean modifier per operation, `Kit Difference`, `Kit Union` and `Kit Intersect`, evaluated in that order above +its `Kit Bevel` (so the cut's edges are bevelled with the rest), or at the end of the stack of a mesh that has no +Bevel. Each modifier cuts with a collection, and `boolean` adds the cutter to it: the modifier's collection is the +one statement of which cutters cut the target; its name (` difference`) is a label, and it is linked to no +scene, so it does not show in the outliner's scene tree. A cutter is listed once: `boolean` refuses one that +already cuts the target under any operation. The target must not be scaled. + +The solver is always Exact with self-intersection on: a kit part is several overlapping closed shells, and +without it the shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap +and the barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that overlap, so each turned body of the kit is one lathe. What carries from machine to machine is the ratio to the same part built as a stack of tubes: 0.31 for the tank's turned body (6 shells against 20), 0.33 for the nozzle (9 against 24) and 0.81 for a pipe fitting (14 against 19). As absolute times, a box cut from a part at its defaults, placed through the add-on with its Bevel below the Boolean, evaluated in 0.50 to 0.55 s for the tank (two sessions), 0.49 s for the nozzle and 0.31 s for a pipe fitting on Blender 5.3 on the workstation Starfire (medians of four processes of five evaluations). The tank's four lugs, shells 7 to 10, add 1 percent to a cut -that misses them and 4 percent to one through them. The part pays this each time it is evaluated. Keep live booleans few and -`apply` them when the shape is settled. `boolean` -evaluates the part once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a -modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter -with no material leaves the part's material slots as they are; a cutter that has materials brings them, after -the part's own, on the faces it makes. +that misses them and 4 percent to one through them. -**`apply`** bakes a part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier goes, -and `kit_baked` is set. The material slots are the part's own (an empty one it had included), followed by any +One Boolean over a collection is why cutters share a modifier. On a shell like a mech's pod (a loft of 6 rings of +8, Subsurf 3, Solidify 0.06: 5000 faces once cut) with 8 box and cylinder cutters placed by `cut`, one evaluation +took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for each cutter, and 1.81 s with the +eight cutters joined into one mesh (medians of five interleaved evaluations, Blender 5.3 on Starfire; an earlier +probe with raw cutters read 2.04, 14.7 and 1.94 s). All three give the same faces and volume. The cost is the +target's, hardly the cutters': one cutter on that shell already costs 1.4 s. The target pays it each time it is +evaluated, and Blender evaluates it after every action that changes it or a cutter. `apply` a kit part when its +shape is settled; a mesh that is not a kit part is baked by `exportGltf` with `applyModifiers`. `boolean` +evaluates the target once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a +modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter +with no material leaves the target's material slots as they are; a cutter that has materials brings them, after +the target's own, on the faces it makes. + +**`apply`** bakes a kit part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier +goes with the collections its Booleans held, and `kit_baked` is set. The cutter objects stay: a cutter placed by +`cut` keeps its floor socket and what is attached to it. The material slots are the part's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty slot of its own take the part's first slot. A baked part keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params, so what is attached to it stays attached and new parts can attach to it, and it can be cut and baked again. `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`. +## 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 +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 | +| --- | --- | --- | +| `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) | +| `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) | +| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor` (mount, size `height`) | +| `slab` | `gap` (x), `length` (y) | none | + +A cutter's frame has its origin where the ray met the surface, `z` along the surface normal (turned to face +against the ray), `y` along the projection of `up` (default the target's +z; refused when it runs along the +normal) and is then turned `roll` degrees about the normal, right-handed (`core.surface_frame`). Its geometry +spans `z` from `-depth` to `+lift`: `depth` below the hit point and `lift` above it, so that a curved surface is +cut cleanly across the whole cutter (raise `lift` for a wide cutter on a tight curve). A `depth` beyond the wall's +thickness opens a hole. `count` copies stand `pitch` apart along `y`, centred on the frame: a row of gills (roll +90 turns the row along `x`). A `slab` is a panel break: a thin slab standing on the normal, long along `y`. + +The ray and `up` are given in the target's own frame, and the ray is cast at the target evaluated with its `Kit` +Booleans off: a second cut on the ray of a through bay lands on the surface as designed, not on the far wall +behind the bay. The target must not be scaled. + +The cutter object is parented to the target under an identity parent inverse and joins the collection of the +target's `Kit Difference` modifier. It owns the cut: its `matrix_basis` is the recess frame and its params the +recess size, and nothing else stores either. `setObjectTransform` on the cutter moves the cut, `set_params` +resizes it, and deleting the cutter removes the cut. `cut` does not hide the cutter: `setObjectVisibility` does, +and a hidden cutter still cuts. + +`box`, `cyl` and `slot` carry one socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's +centre, facing out of the recess. Machinery attaches there with the ordinary `attach` (a vent's `back`, a +sensor's `mount`), is a child of the cutter, and so follows the cut when the cutter moves and is seated again +when `set_params` changes its `depth`. With an even `count` and a `pitch` wider than the copies, the centre lies +between the two middle copies: use an odd count, or a cutter of its own, for a recess that carries a part. A +socket holds one part. + +`cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its `floor` in the world. +It does not evaluate the Boolean (its own work is a few milliseconds), but Blender evaluates the changed target +after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. + ## Expressions Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: @@ -272,11 +332,12 @@ vertices overflow. | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | | `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `baked`. Changes nothing and evaluates no modifier. | -| `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there. Reports the child. | +| `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there; the two parts are of one kit or of two whose socket types agree. Reports the child. | | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | -| `brokkr_kitbash.boolean` | `object_name`, `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds a live Exact Boolean above the Bevel. Refuses a cutter that is the part, is not a mesh, or already cuts it. Reports the part, `booleans: [{cutter, operation}]` and `evaluated`. | -| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the part and clears its modifiers. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | +| `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. | +| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the surface normal and a scaled target. Reports `object`, the `cutter` with its `floor` socket, and `booleans`. | +| `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 and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | `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. @@ -373,6 +434,9 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_eleven_parts_and_three_socket_types`. -`MateTests` covers the mate arithmetic and what may mate. The operators are exercised in a real Blender by +`CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the +frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, a braced leg closed by `close`, boolean and apply). +`set_params` on assemblies, a braced leg closed by `close`, boolean and apply) and `tests/live/kitbash_shell.py` +(`cut` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no +collection). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index b4be991..00e50c1 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -73,9 +73,9 @@ def extent(obj, axis=2): return float(co[:, axis].max() - co[:, axis].min()) -check("the nine kitbash rows load as host actions with no errors", not R["hostErrors"] +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", "close", "boolean", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "apply")], [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 765c5af..f5f3cb1 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the nine kitbash rows load as host actions with no errors", + "name": "the kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -414,6 +414,7 @@ "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", "brokkr_kitbash.apply" ], "placed": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 1b2b5aa..188d821 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -176,8 +176,8 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the nine 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", "close", "boolean", "apply")], [R["hostErrors"], rows]) +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", "close", "boolean", "cut", "apply")], [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 diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 98697ee..f7be6b4 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the nine kitbash rows load as host actions with no errors", + "name": "the kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -452,7 +452,7 @@ "detail": null }, { - "name": "boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", + "name": "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", "ok": true, "detail": null }, @@ -491,11 +491,6 @@ "ok": true, "detail": null }, - { - "name": "refused, scene unchanged: boolean on a mesh that is not a kit part", - "ok": true, - "detail": null - }, { "name": "set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", "ok": true, @@ -542,7 +537,7 @@ "detail": null }, { - "name": "two cutters stack in the order they came, both above the Bevel", + "name": "two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", "ok": true, "detail": null }, @@ -632,8 +627,8 @@ "nonManifoldEdges": 0 }, "slotAndHole": { - "faces": 558, - "volume": 0.001411154, + "faces": 586, + "volume": 0.001411158, "nonManifoldEdges": 0 } }, diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py new file mode 100644 index 0000000..6dc28f3 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -0,0 +1,371 @@ +"""Live proof, in a background Blender, of brokkr_kitbash shell cuts through run_intent: cut on a mesh that is not a kit +part (a subdivided, solidified cage), the one Boolean modifier per operation and its collection, a cast at the surface +without its cuts, machinery on a cutter's floor socket and what moves when the cutter moves or is resized, boolean on +any mesh, the refusals, an object in no collection, and the order of a set_params report's closures. Not part of the +unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_shell.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. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +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: the frames every reading here is taken against +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-shell-")) +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] +kits = {name: core.load_kit(name) for name in ("mechanical", "cutters")} +# Largest entry of a cutter's matrix_basis minus core.surface_frame at the point where this script's own ray meets the +# cage evaluated before the cut. Shipped worst 5.1e-07 (float32 matrices); least claimed mutant 2.0 (X4, the roll's +# sign reversed, on the slab at roll 90); separation 2000 each side. +FRAMED = 1.0e-3 +# Metres between where a second cut on the through bay's ray lands and where the first did. Shipped 0 (the same +# evaluation twice), taken as one float32 step, 1.2e-07; least claimed mutant 1.4 (S2, cast with the cuts on: the ray +# goes through the bay to the far wall); separation 3400 each side. +RECAST = 4.1e-4 +# Metres, or a difference of unit vectors, between the back of a vent attached to a cutter's floor and the hit point +# taken depth along the normal, in the world. Shipped worst 1.8e-07; least claimed mutant 0.036 (S3, the floor socket +# at z=+depth, at depth 0.02); separation 450 each side. +FLOORED = 8.0e-5 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised + + +def reading(name, value): + R["readings"][name] = max(R["readings"].get(name, 0.0), float(value)) + return float(value) + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "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 place(name, part, params="", location=None, rotation=None): + send("brokkr_kitbash.place_part", part=part, object_name=name, params=params) + if location is not None: + send("setObjectTransform", targetObjectName=name, location=location, rotationEuler=rotation or [0.0, 0.0, 0.0]) + return bpy.data.objects[name] + + +def held(report): + """An attach or set_params report whose connection holds.""" + return bool(report and report.get("connection") and report["connection"]["holds"] and report["connection"]["residual"] <= 1e-5) + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(), + {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers], + o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + [s.material and s.material.name for s in o.material_slots], o.hide_render) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes) + + +def refused(label, action, fields, expected): + state = scene_state() + 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"]]) + + +def measure(mesh): + bm = bmesh.new() + bm.from_mesh(mesh) + row = {"faces": len(bm.faces), "volume": round(bm.calc_volume(signed=True), 9), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold)} + bm.free() + return row + + +def evaluated(obj): + """(faces, volume, non-manifold edges, material slot names) of the object with its modifiers, read here and not through the add-on.""" + shown = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + row = measure(shown.to_mesh()) + shown.to_mesh_clear() + return row, [m.name if m else None for m in shown.data.materials] + + +def frame(obj, socket): + """A socket's world frame, from the object's matrix_world and core's build of its stored params.""" + built = core.build(core.part(kits[obj["kit_kit"]], obj["kit_part"]), json.loads(obj["kit_params"])) + return np.array(obj.matrix_world, dtype=np.float64) @ next(s["matrix"] for s in built.sockets if s["name"] == socket) + + +def cast(obj, origin, direction): + """(hit, normal facing the ray) on the object as it is evaluated now, in its own frame: this script's own ray.""" + depsgraph = bpy.context.evaluated_depsgraph_get() + hit, normal, _, _ = BVHTree.FromObject(obj, depsgraph).ray_cast(Vector(origin), Vector(direction).normalized()) + return np.array(hit), np.array(-normal if normal.dot(Vector(direction)) > 0 else normal) + + +def cut(name, part, origin, direction, params="", **more): + return send("brokkr_kitbash.cut", object_name="Cage", cutter_name=name, part=part, params=params, + **{f"origin_{k}": v for k, v in zip("xyz", origin)}, **{f"direction_{k}": v for k, v in zip("xyz", direction)}, **more) + + +def stack(obj): + return [m.name for m in obj.modifiers] + + +# --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ---------------------------------- +bm = bmesh.new() +rings = [[bm.verts.new((r * math.cos(math.pi / 8 + k * math.pi / 4), r * math.sin(math.pi / 8 + k * math.pi / 4), z)) for k in range(8)] + for z, r in ((-1.0, 0.5), (-0.6, 0.7), (-0.2, 0.8), (0.2, 0.8), (0.6, 0.7), (1.0, 0.5))] +for low, high in zip(rings, rings[1:]): + for k in range(8): + bm.faces.new((low[k], low[(k + 1) % 8], high[(k + 1) % 8], high[k])) +bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) +mesh = bpy.data.meshes.new("Cage") +bm.to_mesh(mesh) +bm.free() +cage = bpy.data.objects.new("Cage", mesh) +bpy.context.scene.collection.objects.link(cage) +cage.modifiers.new("Subsurf", "SUBSURF").levels = 2 +wall = cage.modifiers.new("Solidify", "SOLIDIFY") +wall.thickness, wall.offset, wall.use_even_offset = 0.05, -1.0, True +cage.matrix_world = Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X") +bpy.context.view_layer.update() +world = np.array(cage.matrix_world, dtype=np.float64) +uncut, _ = evaluated(cage) +check("the cage is a closed wall before it is cut", uncut["nonManifoldEdges"] == 0 and 0.15 < uncut["volume"] < 0.4 and "kit_part" not in cage, uncut) +R["cage"] = {"uncut": uncut} + +# --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break -------------------------------------- +CUTS = [("Bay", "box", (3.0, 0.0, 0.1), (-1.0, 0.0, 0.0), "width=0.3; height=0.3; depth=0.2", {}), + ("Recess", "cyl", (-3.0, 0.1, 0.2), (2.0, 0.0, 0.0), "r=0.1; depth=0.02", {}), + ("Gills", "slot", (0.1, 3.0, -0.2), (0.0, -1.0, 0.0), "width=0.3; height=0.04; count=4; pitch=0.08; depth=0.02", {}), + ("Break", "slab", (0.0, -3.0, 0.3), (0.0, 1.0, 0.0), "length=0.6; depth=0.1", {"roll": 90.0})] +frames, volume, falls, reports = {}, uncut["volume"], [], {} +for name, part, origin, direction, params, more in CUTS: + hit, normal = cast(cage, origin, direction) # before this cutter exists; the cuts made so far are far from this ray + frames[name] = core.surface_frame(hit, normal, (0.0, 0.0, 1.0), more.get("roll", 0.0)) + state = sorted(o.name for o in bpy.data.objects) + receipt, report = cut(name, part, origin, direction, params, **more) + reports[name] = report + cutter = bpy.data.objects.get(name) + ok = receipt["status"] == "accepted" and cutter is not None and sorted(o.name for o in bpy.data.objects) == sorted(state + [name]) + ok = ok and cutter.parent == cage and np.array_equal(np.array(cutter.matrix_parent_inverse), np.eye(4)) + ok = ok and reading("framed", np.abs(np.array(cutter.matrix_basis) - frames[name]).max()) < FRAMED + ok = ok and (cutter["kit_kit"], cutter["kit_part"]) == ("cutters", part) and bpy.context.scene.collection in cutter.users_collection + ok = ok and not cutter.hide_render and not cutter.hide_viewport and len(cutter.modifiers) == 0 + check(f"cut places the {part} cutter {name} on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + ok, [receipt["message"], cutter and np.array(cutter.matrix_basis).tolist(), frames[name].tolist()]) + wanted = world @ frames[name] + check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report + and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]] + and [s["name"] for s in report["cutter"]["sockets"]] == ([] if part == "slab" else ["floor"]) + and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), + report) + shown, _ = evaluated(cage) + falls.append(shown["volume"] < volume - 1e-4 and shown["nonManifoldEdges"] == 0) + volume = shown["volume"] + R["cage"][name] = shown +modifier = cage.modifiers.get("Kit Difference") +check("four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came", + stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and modifier is not None + and (modifier.type, modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.material_mode) == ("BOOLEAN", "EXACT", True, "DIFFERENCE", "COLLECTION", "TRANSFER") + and [o.name for o in modifier.collection.objects] == [c[0] for c in CUTS] and modifier.collection.name == "Cage difference" + and not any(modifier.collection in s.collection.children_recursive for s in bpy.data.scenes), [stack(cage), modifier and modifier.operand_type]) +check("the evaluated cage stays a closed wall and loses volume with each cut", all(falls) and len(falls) == 4, R["cage"]) +receipt, report = send("brokkr_kitbash.report", object_name="") +check("report lists the cutters as kit parts and not the cage", report and [p["object"] for p in report["parts"]] == sorted(c[0] for c in CUTS) + and all(p["connection"] is None and p["baked"] is False for p in report["parts"]), report and [p["object"] for p in report["parts"]]) + +# --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- +through = cast(cage, CUTS[0][2], CUTS[0][3])[0] # as the cage is evaluated now, with its cuts: through the bay to the far wall +receipt, report = cut("Bay2", "cyl", CUTS[0][2], CUTS[0][3], "r=0.05; depth=0.2") +again = bpy.data.objects.get("Bay2") +check("a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay", + receipt["status"] == "accepted" and again is not None and np.linalg.norm(through - frames["Bay"][:3, 3]) > 1.0 + and reading("recast", np.abs(np.array(again.matrix_basis)[:3, 3] - frames["Bay"][:3, 3]).max()) < RECAST + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers), + [receipt["message"], through.tolist(), frames["Bay"][:3, 3].tolist(), again and list(again.matrix_basis.translation)]) + +# --- floor-carries-machinery ------------------------------------------------------------------------------------------------ +recess = bpy.data.objects["Recess"] +vent = place("Vent", "vent", "width=0.2; height=0.15") # back size 0.135; the floor's is 0.2 +receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Recess", parent_socket="floor", roll=30.0) +floor = world @ frames["Recess"] @ np.array(Matrix.Translation((0.0, 0.0, -0.02))) # the hit point, depth along the normal +back = frame(vent, "back") +check("a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds", + receipt["status"] == "accepted" and held(report) and vent.parent == recess and report["connection"]["parent"] == "Recess" and report["kit"] == "mechanical" + and reading("floored", max(np.abs(back[:3, 3] - floor[:3, 3]).max(), np.abs(back[:3, 2] + floor[:3, 2]).max())) < FLOORED, + [receipt["message"], back.tolist(), floor.tolist()]) +big = place("Big", "vent", "width=0.8; height=0.6") +refused("a vent larger than the recess's floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Recess", "parent_socket": "floor"}, + "'Big' on 'Recess': socket 'back' (mount, size 0.54) and parent socket 'floor' (mount, size 0.2) are mount sockets, where the child fits the parent: it is larger") +nozzle = place("Nozzle", "nozzle") +refused("a flange on a floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "are of different types") +refused("a second part on the floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "'Nozzle' on 'Recess'") +refused("a part on a slab, which has no floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Break", "parent_socket": "floor"}, + "kit 'cutters' part 'slab' has no socket 'floor'; its sockets: none") +refused("detach of a cutter, which is placed and not attached", "brokkr_kitbash.detach", {"object_name": "Recess"}, "'Recess' is not attached") +before = evaluated(cage)[0] +moved_to = np.array(recess.matrix_basis)[:3, 3] + np.array(recess.matrix_basis)[:3, :3] @ [0.0, 0.25, 0.0] # along the cutter's own y: up the wall +was = frame(vent, "back") +send("setObjectTransform", targetObjectName="Recess", location=moved_to.tolist()) +shift = frame(vent, "back")[:3, 3] - was[:3, 3] +after = evaluated(cage)[0] +check("setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere", + reading("floored", np.abs(shift - world[:3, :3] @ (moved_to - frames["Recess"][:3, 3])).max()) < FLOORED and abs(np.linalg.norm(shift) - 0.25) < 1e-4 + and (connection := send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"])["holds"] is True + and after["nonManifoldEdges"] == 0 and after != before, [shift.tolist(), before, after]) +was = frame(vent, "back") +receipt, report = send("brokkr_kitbash.set_params", object_name="Recess", params="depth=0.04") +sunk = frame(vent, "back")[:3, 3] - was[:3, 3] +deeper = evaluated(cage)[0] +check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal", + receipt["status"] == "accepted" and report["params"]["depth"] == 0.04 and reading("floored", np.abs(sunk + was[:3, 2] * -0.02).max()) < FLOORED + and send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"]["holds"] is True + and deeper["volume"] < after["volume"] - 1e-5 and deeper["nonManifoldEdges"] == 0 and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"], + [receipt["message"], sunk.tolist(), after, deeper]) +R["cage"]["deeper"] = deeper + +# --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- +lump_at = world @ [0.0, 0.0, 1.0, 1.0] +send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2) +receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lump", operation="UNION") +check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", + receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"] + and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0] + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2")] + [{"cutter": "Lump", "operation": "UNION"}] + and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) +refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, + "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") +refused("a cut's own cutter given to boolean again", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Bay", "operation": "INTERSECT"}, + "'Bay' already cuts 'Cage' (its Kit Difference modifier's collection)") +plate = place("Plate", "plate", location=[0.0, -6.0, 0.0]) +for name, size, operation in (("Boss", 0.06, "UNION"), ("Keep", 2.0, "INTERSECT"), ("Hole", 0.05, "DIFFERENCE")): + send("createObject", objectType="MESH", name=name, location=[0.0, -6.0, 0.0], size=size) + receipt, report = send("brokkr_kitbash.boolean", object_name="Plate", cutter=name, operation=operation) +check("a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", + receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] + and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}] + and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]]) +collections = len(bpy.data.collections) +receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") +check("apply removes the three collections its modifiers held and leaves every cutter in the scene", receipt["status"] == "accepted" + and baked["cutters"] == ["Hole", "Boss", "Keep"] and len(bpy.data.collections) == collections - 3 and len(plate.modifiers) == 0 + and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], [c.name for c in bpy.data.collections]]) +refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {"object_name": "Cage"}, "'Cage' is not a kit part") + +# --- cut-refusals ----------------------------------------------------------------------------------------------------------- +RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0} +refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'") +refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "The ray's direction is zero") +refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") +refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") +refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") +refused("a target that is not a mesh", "brokkr_kitbash.cut", {**RAY, "object_name": "Nothing"}, "No mesh object named 'Nothing'") +block = bpy.data.objects.new("Block", bpy.data.meshes.new("Block")) +bm = bmesh.new() +bmesh.ops.create_cube(bm, size=1.0) +bm.to_mesh(block.data) +bm.free() +bpy.context.scene.collection.objects.link(block) +block.location = (0.0, -9.0, 0.0) +bpy.context.view_layer.update() +DOWN = {**RAY, "object_name": "Block", "origin_x": 0.1, "origin_y": 0.1, "origin_z": 3.0, "direction_x": 0.0, "direction_z": -1.0} +refused("an up along the hit normal", "brokkr_kitbash.cut", DOWN, "up [0.0, 0.0, 1.0] runs along the surface normal [0.0, 0.0, 1.0]") +block.scale = (1.0, 1.0, 1.01) +bpy.context.view_layer.update() +refused("a scaled target", "brokkr_kitbash.cut", {**DOWN, "up_y": 1.0, "up_z": 0.0}, "'Block' is scaled, mirrored or sheared in the world (scale 1, 1, 1.01)") +refused("boolean on a scaled target", "brokkr_kitbash.boolean", {"object_name": "Block", "cutter": "Lump"}, "'Block' is scaled, mirrored or sheared") +block.scale = (1.0, 1.0, 1.0) +bpy.context.view_layer.update() +receipt, report = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Pocket", "up_y": 1.0, "up_z": 0.0, "roll": 90.0}) +pocket = bpy.data.objects.get("Pocket") +check("a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", receipt["status"] == "accepted" and pocket is not None + and np.abs(np.array(pocket.matrix_basis) - [[0, -1, 0, 0.1], [1, 0, 0, 0.1], [0, 0, 1, 0.5], [0, 0, 0, 1]]).max() < 1e-6 + and np.abs(np.array(report["cutter"]["sockets"][0]["matrix"])[:3, 3] - [0.1, -8.9, 0.48]).max() < 1e-6 and stack(block) == ["Kit Difference"], + [receipt["message"], pocket and np.array(pocket.matrix_basis).tolist()]) + +# --- cut-orphan and closures-ends-first ----------------------------------------------------------------------------------------- +strut = core.build(kits["mechanical"]["parts"]["strut"], {"width": 0.09}) +end = {name: next(s for s in strut.sockets if s["name"] == name) for name in ("end_a", "end_b")} +for pair, y in (("Zz", -20.0), ("Aa", -24.0)): # two closures that share no part; the open one is named to sort first + anchor, loose = place(f"{pair}_Anchor", "strut", "width=0.09", location=[0.0, y, 0.0]), place(f"{pair}_Loose", "strut", "width=0.09") + meet = Matrix((np.array(anchor.matrix_world) @ core.mate(end["end_b"], end["end_a"], 40.0)).tolist()) + send("setObjectTransform", targetObjectName=f"{pair}_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + send("brokkr_kitbash.close", object_name=f"{pair}_Loose", socket="end_a", other_name=f"{pair}_Anchor", other_socket="end_b") +send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") # opens Aa's closure +receipt, report = send("brokkr_kitbash.set_params", object_name="Zz_Anchor", params="width=0.09") +check("closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Zz_Loose", "to": "Zz_Anchor", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], + report and report.get("closures")) +ghost = bpy.data.objects["Aa_Anchor"] +with bpy.context.temp_override(selected_objects=[ghost], active_object=ghost): + bpy.ops.object.delete() # the ordinary Delete: Aa_Loose's closure still points at it, so it stays in the file, in no collection +tie = place("Tie", "strut", "width=0.09") +check("a part deleted with the Delete operator that a closure points to is still in the file", bpy.data.objects.get("Aa_Anchor") is not None and not ghost.users_collection, list(bpy.data.objects.keys())) +GONE = "'Aa_Anchor' is in no collection (a deleted object something still points to)" +refused("cut-orphan: attach onto a deleted part's name", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Aa_Anchor", "parent_socket": "end_a"}, GONE) +refused("attach of a deleted part", "brokkr_kitbash.attach", {"object_name": "Aa_Anchor", "socket": "end_a", "parent_name": "Tie", "parent_socket": "end_a"}, GONE) +refused("set_params on a deleted part", "brokkr_kitbash.set_params", {"object_name": "Aa_Anchor", "params": "length=1.0"}, GONE) +refused("report of a deleted part", "brokkr_kitbash.report", {"object_name": "Aa_Anchor"}, GONE) +refused("cut on a deleted part", "brokkr_kitbash.cut", {**RAY, "object_name": "Aa_Anchor"}, GONE) +refused("boolean on a deleted part", "brokkr_kitbash.boolean", {"object_name": "Aa_Anchor", "cutter": "Lump"}, GONE) +refused("boolean with a deleted part as the cutter", "brokkr_kitbash.boolean", {"object_name": "Tie", "cutter": "Aa_Anchor"}, GONE) +refused("close onto a deleted part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Aa_Anchor", "other_socket": "end_a"}, GONE) + +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"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json new file mode 100644 index 0000000..90e7a0e --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -0,0 +1,279 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the cage is a closed wall before it is cut", + "ok": true, + "detail": null + }, + { + "name": "cut places the box cutter Bay on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Bay as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "cut places the cyl cutter Recess on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Recess as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "cut places the slot cutter Gills on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Gills as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "cut places the slab cutter Break on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Break as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came", + "ok": true, + "detail": null + }, + { + "name": "the evaluated cage stays a closed wall and loses volume with each cut", + "ok": true, + "detail": null + }, + { + "name": "report lists the cutters as kit parts and not the cage", + "ok": true, + "detail": null + }, + { + "name": "a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay", + "ok": true, + "detail": null + }, + { + "name": "a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a vent larger than the recess's floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a flange on a floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second part on the floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part on a slab, which has no floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: detach of a cutter, which is placed and not attached", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere", + "ok": true, + "detail": null + }, + { + "name": "set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal", + "ok": true, + "detail": null + }, + { + "name": "boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut-refusals: a cutter already in the target's union collection", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cut's own cutter given to boolean again", + "ok": true, + "detail": null + }, + { + "name": "a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", + "ok": true, + "detail": null + }, + { + "name": "apply removes the three collections its modifiers held and leaves every cutter in the scene", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on the cage, which is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ray that misses", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ray of no direction", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter name an object has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a param the cutter part does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slot wider across than along", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a target that is not a mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an up along the hit normal", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a scaled target", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a scaled target", + "ok": true, + "detail": null + }, + { + "name": "a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", + "ok": true, + "detail": null + }, + { + "name": "closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", + "ok": true, + "detail": null + }, + { + "name": "a part deleted with the Delete operator that a closure points to is still in the file", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut-orphan: attach onto a deleted part's name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach of a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut on a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean with a deleted part as the cutter", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close onto a deleted part", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "floored": 1.8e-07, + "framed": 5.1e-07, + "recast": 0.0 + }, + "cage": { + "uncut": { + "faces": 1344, + "volume": 0.387534911, + "nonManifoldEdges": 0 + }, + "Bay": { + "faces": 1340, + "volume": 0.382961784, + "nonManifoldEdges": 0 + }, + "Recess": { + "faces": 1373, + "volume": 0.382415225, + "nonManifoldEdges": 0 + }, + "Gills": { + "faces": 1591, + "volume": 0.381816176, + "nonManifoldEdges": 0 + }, + "Break": { + "faces": 1596, + "volume": 0.381252326, + "nonManifoldEdges": 0 + }, + "deeper": { + "faces": 1597, + "volume": 0.380943949, + "nonManifoldEdges": 0 + } + }, + "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 fc9fd43..56e405a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -222,7 +222,7 @@ class CheckKitTests(unittest.TestCase): for name in ("../x", "mechanical.v0", "Mechanical", "", "a/b", "x" * 33, 3): with self.assertRaisesRegex(core.KitError, "must be 1 to 32 of"): core.load_kit(name) - with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: mechanical"): + with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: cutters, mechanical"): core.load_kit("absent") with self.assertRaisesRegex(core.KitError, "has no part 'wing'; its parts: nozzle, tank"): core.part(core.load_kit("mechanical"), "wing") @@ -552,6 +552,150 @@ class MechanicalKitTests(unittest.TestCase): self.assertEqual(described["parts"][0]["params"][0], {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}) +@unittest.skipIf(np is None, "numpy is not installed") +class CuttersKitTests(unittest.TestCase): + """The cutters kit: what brokkr_kitbash.cut places. A cutter spans z from -depth to +lift; its floor socket is the + bottom of the recess seen from outside, so its z is +z where the cutter's own bottom face looks along -z.""" + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("cutters") + + def draws(self, name): + part = self.kit["parts"][name] + rng = random.Random(f"cutters.{name}") + draws = [{p["name"]: p[key] for p in part["params"]} for key in ("default", "min", "max")] + for _ in range(16): + draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) for p in part["params"]}) + return part, draws + + def test_the_kit_is_four_cutters_and_three_floors(self): + self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, + {"box": [("floor", "mount")], "cyl": [("floor", "mount")], "slot": [("floor", "mount")], "slab": []}) + self.assertEqual(self.kit["socketTypes"]["mount"], core.load_kit("mechanical")["socketTypes"]["mount"]) + self.assertTrue(all(part["bevel"] is None for part in self.kit["parts"].values())) + + def test_every_cutter_holds_everywhere(self): + """cutters-kit. Mutant S3 (the floor socket at z=+depth): the floor is not on the cutter's bottom.""" + built = refused = 0 + for name in self.kit["parts"]: + part, draws = self.draws(name) + for given in draws: + if name == "slot" and given["width"] <= given["height"]: + with self.assertRaisesRegex(core.KitError, r"part 'slot' shape 0 \(repeat\) of \(box\): every size must be above 0"): + core.build(part, given) + refused += 1 + continue + b = core.build(part, given) + built += 1 + self.assertTrue(closed_and_oriented(b), f"{name} {given}") + self.assertGreater(signed_volume(b), 0.0) + depth, lift = b.params["depth"], b.params["lift"] + self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12) + self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12) + for socket in b.sockets: + self.assertEqual(socket["matrix"][:, 3].tolist(), [0.0, 0.0, -depth, 1.0]) + self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist()) + self.assertGreater(socket["size"], 0.0) + self.assertGreater(built, 60) + self.assertGreater(refused, 0) + + def test_the_floor_is_the_bottom_of_every_copy(self): + """Every copy's bottom face lies in the floor socket's plane looking the other way, the row is centred on the + frame, and the socket's origin is on a copy's bottom whenever the count is odd.""" + for name, size in (("box", {"width": 0.1, "height": 0.06}), ("cyl", {"r": 0.03}), ("slot", {"width": 0.1, "height": 0.06})): + part = self.kit["parts"][name] + for count in (1, 2, 3, 4, 7, 64): + b = core.build(part, {**size, "count": count, "pitch": 0.09, "depth": 0.03}) + floor = dict(b.sockets[0], matrix=b.sockets[0]["matrix"] @ core.FLIP) # the bottom face looks along -z + self.assertEqual(b.shell_count, count * (3 if name == "slot" else 1)) + bottoms = [b.V[face] for face in faces_of(b) if np.abs(b.V[face][:, 2] + 0.03).max() < 1e-12] + self.assertEqual(len(bottoms), b.shell_count) + self.assertAlmostEqual(float(b.V[:, 1].max() + b.V[:, 1].min()), 0.0, places=12) + self.assertAlmostEqual(float(b.V[:, 1].max() - b.V[:, 1].min()), (count - 1) * 0.09 + 0.06, places=12) + seat = socket_seat(b, floor) + self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy + + def test_a_slot_is_a_stadium_of_its_width(self): + """Mutant S9 (the end tubes at x = +-width/2): the slot is width + height long and the rounds stand off the box.""" + b = core.build(self.kit["parts"]["slot"], {"width": 0.3, "height": 0.05, "depth": 0.02, "lift": 0.05}) + self.assertAlmostEqual(float(b.V[:, 0].max()), 0.15, places=12) + self.assertAlmostEqual(float(b.V[:, 0].min()), -0.15, places=12) + self.assertAlmostEqual(float(np.abs(b.V[:, 1]).max()), 0.025, places=12) + corners = {(round(float(x), 9), round(float(y), 9)) for x, y in b.V[:8, :2]} # shape 0, the box + self.assertEqual(corners, {(-0.125, -0.025), (0.125, -0.025), (0.125, 0.025), (-0.125, 0.025)}) + rounds = {(round(float(x), 9), round(float(y), 9)) for x, y in b.V[8:, :2]} + self.assertTrue(corners <= rounds) # each round's quarter points are the box's corners: one outline + gon = 0.5 * 32 * 0.025 ** 2 * math.sin(2 * math.pi / 32) + self.assertAlmostEqual(signed_volume(b), (0.25 * 0.05 + 2 * gon) * 0.07, places=12) # shells counted where they overlap: the stadium and one more 32-gon + + def test_a_slab_has_no_socket_and_stands_on_the_normal(self): + b = core.build(self.kit["parts"]["slab"], {"depth": 0.1}) + self.assertEqual((b.sockets, len(b.counts)), ([], 6)) + self.assertEqual([round(float(b.V[:, k].max() - b.V[:, k].min()), 12) for k in range(3)], [0.02, 2.0, 0.15]) + with self.assertRaisesRegex(core.KitError, "part 'slab' has no param 'count'"): + core.build(self.kit["parts"]["slab"], {"count": 2}) + + def test_a_floor_takes_a_part_of_the_mechanical_kit(self): + """cross-kit-types: a mechanical vent's back on a cutter's floor, and what does not fit.""" + mechanical = core.load_kit("mechanical") + names = ("cutters", "mechanical") + recess = core.build(self.kit["parts"]["box"], {"width": 0.3, "height": 0.25}) + vent = core.build(mechanical["parts"]["vent"], {"width": 0.2, "height": 0.15}) + floor, back = core.joint(self.kit["parts"]["box"], recess, "floor", mechanical["parts"]["vent"], vent, "back") + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], floor, back, mechanical["socketTypes"], names)) + seated = core.mate(floor, back) @ back["matrix"] + self.assertLess(float(np.abs(seated[:3, 3] - [0.0, 0.0, -0.02]).max()), 1e-12) + self.assertLess(float(np.abs(seated[:3, 2] + [0.0, 0.0, 1.0]).max()), 1e-12) # the vent's back faces the floor: the vent breathes out of the recess + big = core.build(mechanical["parts"]["vent"], {"width": 0.8, "height": 0.6}) + self.assertIn("it is larger", core.mate_refusal(self.kit["socketTypes"], floor, big.sockets[0], mechanical["socketTypes"], names)) + nozzle = core.build(mechanical["parts"]["nozzle"]) + self.assertIn("are of different types", core.mate_refusal(self.kit["socketTypes"], floor, nozzle.sockets[0], mechanical["socketTypes"], names)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class SurfaceFrameTests(unittest.TestCase): + """surface-frame: the frame brokkr_kitbash.cut gives a cutter. Bounds: a shipped reading is float rounding (worst + 4.4e-16 over the draws) and the least mutant's is 0.31 (S4, the roll dropped, at roll 18); 1e-9 separates them by + 2e6 and 3e8 (lodur:ruling:deterministic-bound-margin, geometric mean 1.2e-8).""" + EXACT = 1.2e-8 + + def test_z_is_the_normal_y_is_up_s_projection_and_the_frame_is_right_handed(self): + rng = random.Random("surface-frame") + for _ in range(64): + point, normal, up = ([rng.uniform(-3, 3) for _ in range(3)] for _ in range(3)) + frame = core.surface_frame(point, normal, up) + turn, n = frame[:3, :3], np.array(normal) / np.linalg.norm(normal) + self.assertLess(np.abs(turn.T @ turn - np.eye(3)).max(), self.EXACT) + self.assertLess(abs(np.linalg.det(turn) - 1.0), self.EXACT) + self.assertLess(np.abs(frame[:3, 2] - n).max(), self.EXACT) + self.assertLess(np.abs(frame[:3, 3] - point).max(), self.EXACT) + self.assertGreater(float(frame[:3, 1] @ up), 0.0) + self.assertLess(abs(float(np.cross(n, up) @ frame[:3, 1])), self.EXACT * 10) # y lies in the plane of up and the normal + self.assertEqual(frame[3].tolist(), [0.0, 0.0, 0.0, 1.0]) + self.assertLess(np.abs(core.surface_frame((1, 2, 3), (0, 0, 5), (0, 2, 9)) - [[1, 0, 0, 1], [0, 1, 0, 2], [0, 0, 1, 3], [0, 0, 0, 1]]).max(), self.EXACT) + + def test_roll_turns_the_frame_about_the_normal_right_handed(self): + """Mutant S4 (surface_frame without the roll).""" + rng = random.Random("surface-roll") + for roll in (18.0, 90.0, -37.0, 180.0, 360.0): + point, normal, up = ([rng.uniform(-3, 3) for _ in range(3)] for _ in range(3)) + flat, turned = core.surface_frame(point, normal, up), core.surface_frame(point, normal, up, roll) + read = math.degrees(math.atan2(np.cross(flat[:3, 1], turned[:3, 1]) @ flat[:3, 2], flat[:3, 1] @ turned[:3, 1])) + self.assertLess(abs((read - roll + 180.0) % 360.0 - 180.0), 1e-6) + self.assertLess(np.abs(turned[:, 2:] - flat[:, 2:]).max(), self.EXACT) + quarter = core.surface_frame((0, 0, 0), (0, 0, 1), (0, 1, 0), 90.0) + self.assertLess(np.abs(quarter[:3, 1] - [-1.0, 0.0, 0.0]).max(), self.EXACT) # as mate's roll: y turns toward -x + + def test_a_zero_normal_and_an_up_along_the_normal_are_refused(self): + with self.assertRaisesRegex(core.KitError, r"normal \(0, 0, 0\) has no direction"): + core.surface_frame((0, 0, 0), (0, 0, 0), (0, 0, 1)) + for up in ((0, 0, 1), (0, 0, -4), (0, 0, 0), (1e-7, 0, 1)): + with self.assertRaisesRegex(core.KitError, r"up \[.*\] runs along the surface normal \[0\.0, 0\.0, 1\.0\]"): + core.surface_frame((0, 0, 0), (0, 0, 2), up) + core.surface_frame((0, 0, 0), (0, 0, 2), (1e-5, 0, 1)) + + @unittest.skipIf(np is None, "numpy is not installed") class MateTests(unittest.TestCase): """core.mate, residual, mate_refusal and joint. The four bounds sit at the geometric mean of the shipped worst @@ -792,7 +936,7 @@ class MateTests(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.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -843,6 +987,14 @@ class HostFileTests(unittest.TestCase): {k: v for k, v in close.items() if k != "other_socket"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) + cut = {**envelope, "action": "brokkr_kitbash.cut", "object_name": "Cage", "cutter_name": "Bay", "part": "box", + "origin_x": 3, "origin_y": 0, "origin_z": 0.5, "direction_x": -1, "direction_y": 0, "direction_z": 0} + admitted = at.validate(cut, host) + self.assertEqual([admitted[k] for k in ("up_x", "up_y", "up_z", "roll", "params")], [0, 0, 1, 0, ""]) + for bad in ({**cut, "part": "sphere"}, {**cut, "roll": 361}, {**cut, "origin_x": 1e4}, {k: v for k, v in cut.items() if k != "direction_z"}, + {**cut, "up_z": -1001}, {**cut, "cutter_name": ""}, {**cut, "operation": "UNION"}, {**cut, "params": "a=1;" * 1000 + "b"}): + 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"]) @@ -863,7 +1015,7 @@ class OwnershipTests(unittest.TestCase): return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")} def test_no_pattern_matches(self): - self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "mechanical.v0.json"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "mechanical.v0.json"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}") @@ -873,14 +1025,19 @@ class OwnershipTests(unittest.TestCase): for path in schemas: self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name) - def test_only_boolean_and_apply_evaluate_a_modifier_stack(self): - """An Exact Boolean costs about a second a part: report, attach, detach and set_params read stored state only.""" + def test_only_cut_boolean_and_apply_evaluate_a_modifier_stack(self): + """An Exact Boolean costs from tenths of a second to seconds: report, attach, detach and set_params read stored + state only, and cut evaluates its target with the Booleans off.""" source = self.sources()["__init__.py"] self.assertEqual(source.count("evaluated_get("), 1) self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body] - self.assertEqual(callers, ["boolean", "apply"]) - self.assertEqual(source.count("evaluated_of("), 3) + self.assertEqual(callers, ["boolean", "cut", "apply"]) + self.assertEqual(source.count("evaluated_of("), 4) + cut = source.split("class BROKKR_KITBASH_OT_cut")[1].split("class BROKKR_KITBASH_OT_")[0] + self.assertLess(cut.index("modifier.show_viewport = False"), cut.index("evaluated_of(")) + self.assertLess(cut.index("evaluated_of("), cut.index("modifier.show_viewport = True")) + self.assertNotIn("view_layer.update", cut) # an update after the cutter joins would evaluate the Boolean self.assertEqual(source.count("to_mesh("), 1) def test_only_attach_writes_the_roll(self): From 889f54954840e60558a7dfa54dae1a8f0b3d6814 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:53:42 +0100 Subject: [PATCH 5/6] docs/kitbash.md: what a cut costs on a pod with 15 cutters Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 26829ce..e127385 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -308,7 +308,11 @@ socket holds one part. `cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its `floor` in the world. It does not evaluate the Boolean (its own work is a few milliseconds), but Blender evaluates the changed target -after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. +after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. On a pod +with a Bevel under the Boolean and 15 cutters (two of them slabs through the whole shell) one evaluation took +5.4 s, and the 15 cuts took 113 s in a script that also hid each cutter before the next cut, which made Blender +evaluate the pod twice an action; the same cuts as one joined cutter, evaluated once, took 4.7 s. Cutting a shell +through actions costs an evaluation a cut. ## Expressions From 513b89fd35e56c113e76b7f1c2c303169dfff052 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 03:16:14 +0100 Subject: [PATCH 6/6] brokkr_kitbash.cut_many, a cutter axis, three floors on a slot A cut costs one Boolean evaluation of its target, because Blender evaluates a changed target after every action; cut_many places many cutters in one action, all or none, for one evaluation (Heron's pod: 4.9 s for 13 cutters against 113 s for 15 cut actions). cut and cut_many place through one function, place_cutters. axis states a cutter's z in place of the surface normal, so a panel break does not lean with a sloping roof. A slot carries floor_l and floor_r beside floor. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 142 +++++++++++++----- .../brokkr_kitbash/brokkr_actions.json | 49 +++++- .../brokkr_kitbash/kits/cutters.v0.json | 6 +- surfaces/blender/docs/kitbash.md | 34 +++-- surfaces/blender/tests/live/kitbash.py | 2 +- .../blender/tests/live/kitbash.result.json | 1 + .../blender/tests/live/kitbash_assembly.py | 2 +- surfaces/blender/tests/live/kitbash_shell.py | 74 ++++++++- .../tests/live/kitbash_shell.result.json | 92 +++++++++++- surfaces/blender/tests/test_kitbash.py | 40 +++-- 10 files changed, 375 insertions(+), 67 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 430fde2..a910f03 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -29,7 +29,8 @@ collection's name is a label, and it is linked to no scene. cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters kit, parented to the target under an identity parent inverse: its matrix_basis is the recess frame and its params the recess size, so moving or resizing the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches -to the floor socket with the ordinary attach. +to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs +one Boolean evaluation; cut_many places many cutters for one. 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 @@ -395,6 +396,64 @@ def bounded(report: dict, advice: str) -> dict: return report +def place_cutters(context, target, specs, report=None) -> list: + """Place a cutters part for each spec ({name, part, origin, direction} and optionally params, up, roll, axis; the + vectors in the target's own frame) and add them to the target's difference Boolean; [(cutter, part, built)]. + Every refusal comes before any write. The rays are cast in one evaluation of the target with its Kit Booleans + off, the surface as designed and not as already cut: a second cut on the ray of a through bay lands where the + first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however + many cutters it placed. `report`, given the booleans rows to be, may refuse a report too long for a receipt.""" + rigid(target) + kit, made, names = core.load_kit(CUTTERS), [], set() + for spec in specs: + name = spec["name"] + if name in bpy.data.objects or name in names: + raise Refused(f"An object named {name!r} exists{' in this call' if name in names else ''}; nothing changed.") + names.add(name) + part = core.part(kit, spec["part"]) + built = core.build(part, core.parse_params(spec.get("params", ""))) + if Vector(spec["direction"]).length == 0.0: + raise Refused(f"{name!r}: the ray's direction is zero; nothing changed.") + made.append((part, built)) + cuts = [m for m in (target.modifiers.get("Kit " + operation.title()) for operation in OPERATIONS) if m is not None and m.show_viewport] + try: + for modifier in cuts: + modifier.show_viewport = False + depsgraph, _ = evaluated_of(context, target) + tree = BVHTree.FromObject(target, depsgraph) + finally: + for modifier in cuts: + modifier.show_viewport = True + frames = [] + for spec in specs: + origin, direction, axis = Vector(spec["origin"]), Vector(spec["direction"]), Vector(spec.get("axis", (0.0, 0.0, 0.0))) + hit, normal, _, _ = tree.ray_cast(origin, direction.normalized()) + if hit is None: + raise Refused(f"The ray from {tuple(round(v, 6) for v in origin)} along {tuple(round(v, 6) for v in direction)} misses {target.name!r}; nothing changed.") + if normal.dot(direction) > 0: + normal = -normal + if axis.length > 0.0 and axis.dot(normal) <= 0.0: + raise Refused(f"{spec['name']!r}: the axis {tuple(round(v, 6) for v in axis)} points into the surface (its normal there is " + f"{tuple(round(v, 6) for v in normal)}); nothing changed.") + frames.append(core.surface_frame(hit, axis if axis.length > 0.0 else normal, spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0))) + if report is not None: + report(booleans(target) + [{"cutter": spec["name"], "operation": "DIFFERENCE"} for spec in specs]) + placed = [] + for spec, (part, built), frame in zip(specs, made, frames): + mesh = bpy.data.meshes.new(spec["name"]) + write_mesh(mesh, built) + cutter = bpy.data.objects.new(spec["name"], mesh) + context.scene.collection.objects.link(cutter) + sync_bevel(cutter, built.bevel) + cutter[KIT], cutter[PART], cutter[PARAMS] = part["kit"], part["name"], json.dumps(built.params) + cutter.parent = target + cutter.matrix_world = target.matrix_world @ Matrix(frame.tolist()) # read by the report; no depsgraph update, which would evaluate the Boolean + seat(cutter, frame) + operation_collection(target, "DIFFERENCE", True).objects.link(cutter) + placed.append((cutter, part, built)) + return placed + + class BROKKR_KITBASH_OT_place_part(PolishOperator): """Place a kit part at the origin as a new mesh object: its geometry from the kit and params, a Bevel modifier when the part has a bevel, and the kit, part and params stored on the object""" @@ -593,8 +652,8 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): class BROKKR_KITBASH_OT_cut(PolishOperator): """Cut a mesh object, a kit part or any other, where a ray meets it: places a part of the cutters kit on the - surface there (z the surface normal, y the projection of up, turned by roll), parented to the target, and adds it - to the target's difference Boolean; the cutter's floor socket is where machinery attaches""" + surface there (z the surface normal or a stated axis, y the projection of up, turned by roll), parented to the + target, and adds it to the target's difference Boolean; the cutter's floor socket is where machinery attaches""" bl_idname = "brokkr_kitbash.cut" bl_label = "Cut At Ray" object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") @@ -612,44 +671,55 @@ class BROKKR_KITBASH_OT_cut(PolishOperator): up_z: bpy.props.FloatProperty(name="Up Z", default=1.0) roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, description="Degrees about the surface normal, right-handed") + axis_x: bpy.props.FloatProperty(name="Axis X", default=0.0, description="The cutter's z, in the target's own frame; all zero: the surface normal") + axis_y: bpy.props.FloatProperty(name="Axis Y", default=0.0) + axis_z: bpy.props.FloatProperty(name="Axis Z", default=0.0) + @kit_work def work(self, context): target = mesh_object(self.object_name) - rigid(target) - if self.cutter_name in bpy.data.objects: - raise Refused(f"An object named {self.cutter_name!r} exists; nothing changed.") - part = core.part(core.load_kit(CUTTERS), self.part) - built = core.build(part, core.parse_params(self.params)) - origin, direction = Vector((self.origin_x, self.origin_y, self.origin_z)), Vector((self.direction_x, self.direction_y, self.direction_z)) - if direction.length == 0.0: - raise Refused("The ray's direction is zero; nothing changed.") - cuts = [m for m in (target.modifiers.get("Kit " + operation.title()) for operation in OPERATIONS) if m is not None and m.show_viewport] - try: # the surface as designed, not as already cut: a second cut on the ray of a through bay lands where the first did - for modifier in cuts: - modifier.show_viewport = False - depsgraph, _ = evaluated_of(context, target) - hit, normal, _, _ = BVHTree.FromObject(target, depsgraph).ray_cast(origin, direction.normalized()) - finally: - for modifier in cuts: - modifier.show_viewport = True - if hit is None: - raise Refused(f"The ray from {tuple(round(v, 6) for v in origin)} along {tuple(round(v, 6) for v in direction)} misses {target.name!r}; nothing changed.") - if normal.dot(direction) > 0: - normal = -normal - frame = core.surface_frame(hit, normal, (self.up_x, self.up_y, self.up_z), self.roll) - mesh = bpy.data.meshes.new(self.cutter_name) - write_mesh(mesh, built) - cutter = bpy.data.objects.new(self.cutter_name, mesh) - context.scene.collection.objects.link(cutter) - sync_bevel(cutter, built.bevel) - cutter[KIT], cutter[PART], cutter[PARAMS] = part["kit"], part["name"], json.dumps(built.params) - cutter.parent = target - cutter.matrix_world = target.matrix_world @ Matrix(frame.tolist()) # read by the report below; no depsgraph update, which would evaluate the Boolean - seat(cutter, frame) - operation_collection(target, "DIFFERENCE", True).objects.link(cutter) + spec = {"name": self.cutter_name, "part": self.part, "params": self.params, "roll": self.roll, + "origin": (self.origin_x, self.origin_y, self.origin_z), "direction": (self.direction_x, self.direction_y, self.direction_z), + "up": (self.up_x, self.up_y, self.up_z), "axis": (self.axis_x, self.axis_y, self.axis_z)} + (cutter, part, built), = place_cutters(context, target, [spec]) return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)} +CUT_KEYS = {"name": str, "part": str, "params": str, "origin": list, "direction": list, "up": list, "axis": list, "roll": (int, float)} +CUTS_LIMIT = 64 # cutters in one cut_many + + +class BROKKR_KITBASH_OT_cut_many(PolishOperator): + """Cut a mesh object at several rays in one action: every cutter is checked and every ray cast before anything is + written, so the call places all of them or none, and Blender evaluates the target's Boolean once for the lot""" + bl_idname = "brokkr_kitbash.cut_many" + bl_label = "Cut At Rays" + object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") + cuts: bpy.props.StringProperty(name="Cuts", description="A JSON array of cutters: name, part, origin and direction, and optionally params, up, roll and axis, as cut's fields") + + @kit_work + def work(self, context): + target = mesh_object(self.object_name) + try: + specs = json.loads(self.cuts) + except ValueError as error: + raise Refused(f"cuts is not JSON ({error}); nothing changed.") from None + if not isinstance(specs, list) or not 1 <= len(specs) <= CUTS_LIMIT: + raise Refused(f"cuts must be a JSON array of 1 to {CUTS_LIMIT} cutters; nothing changed.") + for index, spec in enumerate(specs): + where = f"cuts[{index}]" + if not isinstance(spec, dict) or not {"name", "part", "origin", "direction"} <= set(spec) <= set(CUT_KEYS): + raise Refused(f"{where} must be an object with name, part, origin and direction, and optionally params, up, roll and axis; nothing changed.") + for key, value in spec.items(): + vector = CUT_KEYS[key] is list + if not isinstance(value, CUT_KEYS[key]) or isinstance(value, bool) or (vector and (len(value) != 3 or not all(core.finite(v) for v in value))) \ + or (key == "roll" and not (core.finite(value) and -360.0 <= value <= 360.0)) or (key == "name" and not 1 <= len(value) <= 63): + raise Refused(f"{where}.{key} must be {'three numbers' if vector else 'a number from -360 to 360' if key == 'roll' else 'a string' + (' of 1 to 63 characters' if key == 'name' else '')}; nothing changed.") + placed = place_cutters(context, target, specs, report=lambda rows: bounded({"object": target.name, "cutters": [spec["name"] for spec in specs], "booleans": rows}, + "cut fewer at once")) + return {"object": target.name, "cutters": [cutter.name for cutter, _, _ in placed], "booleans": booleans(target)} + + class BROKKR_KITBASH_OT_apply(PolishOperator): """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections @@ -718,7 +788,7 @@ 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_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index cf8de59..5fe8651 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -254,7 +254,7 @@ }, { "name": "brokkr_kitbash.cut", - "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Does not evaluate the Boolean itself (boolean does, and reports it). Reports the cutter with its sockets, and booleans.", + "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -367,6 +367,53 @@ "maximum": 360, "default": 0, "doc": "degrees about the surface normal, right-handed" + }, + { + "name": "axis_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0, + "doc": "the cutter's z, in the target's own frame, in place of the surface normal (a panel break that must not lean with a sloping surface); all zero: the surface normal; refused when it points into the surface" + }, + { + "name": "axis_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + }, + { + "name": "axis_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + } + ] + }, + { + "name": "brokkr_kitbash.cut_many", + "doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans; brokkr_kitbash.report gives a cutter's sockets.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the mesh that is cut: a kit part or any mesh, not scaled" + }, + { + "name": "cuts", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 16000, + "doc": "a JSON array of 1 to 64 cutters, each {\"name\", \"part\", \"origin\": [x, y, z], \"direction\": [x, y, z]} and optionally \"params\" (name=value; ...), \"up\": [x, y, z] (default 0, 0, 1), \"roll\" (degrees) and \"axis\": [x, y, z], with the meanings of brokkr_kitbash.cut's fields" } ] }, diff --git a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json index 0677a9e..e15261c 100644 --- a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json @@ -43,7 +43,7 @@ }, { "name": "slot", - "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r a third of the width to each side; each holds one part.", "params": [ {"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"}, {"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"}, @@ -58,7 +58,9 @@ {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}} ], "sockets": [ - {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_l", "type": "mount", "size": "height", "at": ["-width/3", 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_r", "type": "mount", "size": "height", "at": ["width/3", 0, "-depth"], "z": "+z", "y": "+y"} ] }, { diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index e127385..5c512d2 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -278,7 +278,7 @@ kit part, where a ray meets it, and what it places is itself a kit part, of the | --- | --- | --- | | `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) | | `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) | -| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor` (mount, size `height`) | +| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size `height`) | | `slab` | `gap` (x), `length` (y) | none | A cutter's frame has its origin where the ray met the surface, `z` along the surface normal (turned to face @@ -289,6 +289,10 @@ cut cleanly across the whole cutter (raise `lift` for a wide cutter on a tight c thickness opens a hole. `count` copies stand `pitch` apart along `y`, centred on the frame: a row of gills (roll 90 turns the row along `x`). A `slab` is a panel break: a thin slab standing on the normal, long along `y`. +`axis` (default all zero: the surface normal) states the cutter's `z` instead. A slab on a sloping roof leans +with the roof's normal; with an axis it stands where it is told, and the break's plane has the normal +`up` cross `axis`. An axis that points into the surface is refused. + The ray and `up` are given in the target's own frame, and the ray is cast at the target evaluated with its `Kit` Booleans off: a second cut on the ray of a through bay lands on the surface as designed, not on the far wall behind the bay. The target must not be scaled. @@ -299,20 +303,25 @@ recess size, and nothing else stores either. `setObjectTransform` on the cutter resizes it, and deleting the cutter removes the cut. `cut` does not hide the cutter: `setObjectVisibility` does, and a hidden cutter still cuts. -`box`, `cyl` and `slot` carry one socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's -centre, facing out of the recess. Machinery attaches there with the ordinary `attach` (a vent's `back`, a +`box`, `cyl` and `slot` carry a socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's +centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, a third +of its width to each side: a visor with three eyes. Machinery attaches there with the ordinary `attach` (a vent's `back`, a sensor's `mount`), is a child of the cutter, and so follows the cut when the cutter moves and is seated again when `set_params` changes its `depth`. With an even `count` and a `pitch` wider than the copies, the centre lies between the two middle copies: use an odd count, or a cutter of its own, for a recess that carries a part. A socket holds one part. -`cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its `floor` in the world. -It does not evaluate the Boolean (its own work is a few milliseconds), but Blender evaluates the changed target -after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. On a pod -with a Bevel under the Boolean and 15 cutters (two of them slabs through the whole shell) one evaluation took -5.4 s, and the 15 cuts took 113 s in a script that also hid each cutter before the next cut, which made Blender -evaluate the pod twice an action; the same cuts as one joined cutter, evaluated once, took 4.7 s. Cutting a shell -through actions costs an evaluation a cut. +`cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its floors in the world. +Its own work is a few milliseconds and it evaluates no Boolean, but Blender evaluates a changed target after +every action, so each `cut` costs one Boolean evaluation of the target: on the shell above 1.4 to 1.9 s, one +cutter to eight. `cut_many` takes a JSON array of cutters (`name`, `part`, `origin`, `direction`, and optionally +`params`, `up`, `roll`, `axis`), checks them all and casts every ray before it writes anything, places all of +them or none, and costs one evaluation for the lot. On a pod with a Bevel under the Boolean (6500 faces once +cut; one evaluation 5.2 s), 13 cutters placed by one `cut_many` took 4.9 s, and 15 placed by 15 `cut` actions +took 113 s; the same cuts as one joined cutter, evaluated once and baked, took 4.6 s (Blender 5.3 on Starfire). +Any later action that changes the target or a cutter (hiding the cutters, attaching a part to a floor) costs an +evaluation again while the target is visible. `cut_many` reports `{object, cutters, booleans}` with the cutters +by name. ## Expressions @@ -340,7 +349,8 @@ vertices overflow. | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. | -| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the surface normal and a scaled target. Reports `object`, the `cutter` with its `floor` socket, and `booleans`. | +| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans`. | +| `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`. | | `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 and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored @@ -442,5 +452,5 @@ part of `mechanical` also joins the part and socket list in `test_the_kit_is_the frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, a braced leg closed by `close`, boolean and apply) and `tests/live/kitbash_shell.py` -(`cut` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no +(`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 00e50c1..b1807b1 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -75,7 +75,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", "close", "boolean", "cut", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "cut_many", "apply")], [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 f5f3cb1..88be33e 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -415,6 +415,7 @@ "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", "brokkr_kitbash.apply" ], "placed": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 188d821..86a2197 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -177,7 +177,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", "close", "boolean", "cut", "apply")], [R["hostErrors"], rows]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "cut_many", "apply")], [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 diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index 6dc28f3..f8dbb11 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -1,7 +1,7 @@ """Live proof, in a background Blender, of brokkr_kitbash shell cuts through run_intent: cut on a mesh that is not a kit part (a subdivided, solidified cage), the one Boolean modifier per operation and its collection, a cast at the surface without its cuts, machinery on a cutter's floor socket and what moves when the cutter moves or is resized, boolean on -any mesh, the refusals, an object in no collection, and the order of a set_params report's closures. Not part of the +any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection, and the order of a set_params report's closures. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_shell.py -- @@ -207,7 +207,7 @@ for name, part, origin, direction, params, more in CUTS: check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]] - and [s["name"] for s in report["cutter"]["sockets"]] == ([] if part == "slab" else ["floor"]) + and [s["name"] for s in report["cutter"]["sockets"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"]) and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), report) shown, _ = evaluated(cage) @@ -275,6 +275,72 @@ check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on [receipt["message"], sunk.tolist(), after, deeper]) R["cage"]["deeper"] = deeper +# --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors ----------------------------------- +def uncut_cast(origin, direction): + shown = [m for m in cage.modifiers if m.name.startswith("Kit ")] + for m in shown: + m.show_viewport = False + try: + return cast(cage, origin, direction) + finally: + for m in shown: + m.show_viewport = True + + +MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]}, + {"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]}, + {"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}] +wanted = {} +for spec in MANY: + hit, normal = uncut_cast(spec["origin"], spec["direction"]) + wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)) + if "axis" in spec: + lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0)))) +refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])}, + "The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'") +refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call") +refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;") +refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside") +refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON") +refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters") +refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])}, + "cuts[0] must be an object with name, part, origin and direction") +refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object") +refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers") +refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360") +refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface") +addon = sys.modules["brokkr_kitbash"] +limit = addon.REPORT_LIMIT +addon.REPORT_LIMIT = 300 +refused("cut_many whose report would not fit a receipt places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY)}, "over the 300 a receipt carries: cut fewer at once") +addon.REPORT_LIMIT = limit +receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY)) +placed = [bpy.data.objects.get(spec["name"]) for spec in MANY] +check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", + receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]} + and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"] + and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4)) + and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed) + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0, + [receipt["message"], report]) +seam = bpy.data.objects["Seam"] +check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0 + and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()]) +receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7, + direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0) +check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"]) +visor = bpy.data.objects["Visor"] +eyes = {} +for socket, x in (("floor", 0.0), ("floor_l", -0.2), ("floor_r", 0.2)): + eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14 + receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket) + there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02))) + eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \ + and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED +check("a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes) +refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'") +refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'") + # --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- lump_at = world @ [0.0, 0.0, 1.0, 1.0] send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2) @@ -282,7 +348,7 @@ receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lum check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"] and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0] - and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2")] + [{"cutter": "Lump", "operation": "UNION"}] + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}] and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") @@ -306,7 +372,7 @@ refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {" # --- cut-refusals ----------------------------------------------------------------------------------------------------------- RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0} refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'") -refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "The ray's direction is zero") +refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "'New': the ray's direction is zero") refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json index 90e7a0e..74a159c 100644 --- a/surfaces/blender/tests/live/kitbash_shell.result.json +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -106,6 +106,96 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: cut_many whose second ray misses places none", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many with a name twice", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many with a name an object has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many whose last cutter has a bad param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of text that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of no cutters", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of a cutter with no direction", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of a cutter with a key cut does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of an origin of two numbers", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of a roll of 400", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an axis that points into the surface", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many whose report would not fit a receipt places none", + "ok": true, + "detail": null + }, + { + "name": "cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", + "ok": true, + "detail": null + }, + { + "name": "a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", + "ok": true, + "detail": null + }, + { + "name": "cut takes the same axis", + "ok": true, + "detail": null + }, + { + "name": "a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second part on a side floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a fourth eye on a floor that is taken", + "ok": true, + "detail": null + }, { "name": "boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", "ok": true, @@ -239,7 +329,7 @@ ], "hostErrors": [], "readings": { - "floored": 1.8e-07, + "floored": 2.6e-07, "framed": 5.1e-07, "recast": 0.0 }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 56e405a..b0c9404 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -569,9 +569,9 @@ class CuttersKitTests(unittest.TestCase): draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) for p in part["params"]}) return part, draws - def test_the_kit_is_four_cutters_and_three_floors(self): + def test_the_kit_is_four_cutters_and_their_floors(self): self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, - {"box": [("floor", "mount")], "cyl": [("floor", "mount")], "slot": [("floor", "mount")], "slab": []}) + {"box": [("floor", "mount")], "cyl": [("floor", "mount")], "slot": [("floor", "mount"), ("floor_l", "mount"), ("floor_r", "mount")], "slab": []}) self.assertEqual(self.kit["socketTypes"]["mount"], core.load_kit("mechanical")["socketTypes"]["mount"]) self.assertTrue(all(part["bevel"] is None for part in self.kit["parts"].values())) @@ -594,7 +594,8 @@ class CuttersKitTests(unittest.TestCase): self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12) self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12) for socket in b.sockets: - self.assertEqual(socket["matrix"][:, 3].tolist(), [0.0, 0.0, -depth, 1.0]) + side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * b.params.get("width", 0.0) / 3 + self.assertEqual(socket["matrix"][:, 3].tolist(), [side, 0.0, -depth, 1.0]) self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist()) self.assertGreater(socket["size"], 0.0) self.assertGreater(built, 60) @@ -616,6 +617,17 @@ class CuttersKitTests(unittest.TestCase): seat = socket_seat(b, floor) self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy + def test_a_slot_has_three_floors_on_its_bottom(self): + """A visor carries three eyes: floor_l and floor_r lie a third of the width to each side, on the slot's own + bottom, each the size of the slot's height. Mutant B4 (the two side floors swapped).""" + part = self.kit["parts"]["slot"] + for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}): + b = core.build(part, given) + self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), s["size"]) for s in b.sockets], + [("floor", 0.0, given["height"]), ("floor_l", round(-given["width"] / 3, 12), given["height"]), ("floor_r", round(given["width"] / 3, 12), given["height"])]) + for socket in b.sockets: + self.assertLess(socket_seat(b, dict(socket, matrix=socket["matrix"] @ core.FLIP)), 1e-12, socket["name"]) + def test_a_slot_is_a_stadium_of_its_width(self): """Mutant S9 (the end tubes at x = +-width/2): the slot is width + height long and the rounds stand off the box.""" b = core.build(self.kit["parts"]["slot"], {"width": 0.3, "height": 0.05, "depth": 0.02, "lift": 0.05}) @@ -936,7 +948,7 @@ class MateTests(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.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -995,6 +1007,12 @@ class HostFileTests(unittest.TestCase): {**cut, "up_z": -1001}, {**cut, "cutter_name": ""}, {**cut, "operation": "UNION"}, {**cut, "params": "a=1;" * 1000 + "b"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) + self.assertEqual([at.validate(cut, host)[k] for k in ("axis_x", "axis_y", "axis_z")], [0, 0, 0]) + many = {**envelope, "action": "brokkr_kitbash.cut_many", "object_name": "Cage", "cuts": '[{"name": "Bay", "part": "box", "origin": [3, 0, 0], "direction": [-1, 0, 0]}]'} + self.assertEqual(at.validate(many, host)["cuts"], many["cuts"]) + for bad in ({**cut, "axis_y": 1001}, {**many, "cuts": ""}, {**many, "cuts": "[" + " " * 16000}, {k: v for k, v in many.items() if k != "cuts"}, {**many, "cutter_name": "Bay"}): + 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"]) @@ -1032,12 +1050,16 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("evaluated_get("), 1) self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body] - self.assertEqual(callers, ["boolean", "cut", "apply"]) + self.assertEqual(callers, ["boolean", "apply"]) self.assertEqual(source.count("evaluated_of("), 4) - cut = source.split("class BROKKR_KITBASH_OT_cut")[1].split("class BROKKR_KITBASH_OT_")[0] - self.assertLess(cut.index("modifier.show_viewport = False"), cut.index("evaluated_of(")) - self.assertLess(cut.index("evaluated_of("), cut.index("modifier.show_viewport = True")) - self.assertNotIn("view_layer.update", cut) # an update after the cutter joins would evaluate the Boolean + place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off + self.assertEqual(place.count("evaluated_of("), 1) + self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluated_of(")) + self.assertLess(place.index("evaluated_of("), place.index("modifier.show_viewport = True")) + self.assertLess(place.index("report(booleans(target)"), place.index("bpy.data.meshes.new(")) # every refusal before any write + 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) self.assertEqual(source.count("to_mesh("), 1) def test_only_attach_writes_the_roll(self):