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):