From a3172c031b99673e64ac15980a3c3f60a5a8a591 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:02:34 +0100 Subject: [PATCH] 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))